有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用Java读取用户输入

我需要设计并实现一个名为CinemaPrice的应用程序来确定一个人去电影院要花多少钱。程序应该使用随机类生成1-100岁的年龄,并提示用户提供完整的票价。然后使用货币格式显示相应的票价(书中的示例)。你可以参考我们在课堂上一起做的例子来帮助你理解“if语句”。在以下基础上决定票价:
1.5岁以下,免费; 2.5岁至12岁,半价; 3.13至54岁,全价; 4.55岁或以上免费

我真的很想在这方面得到一些帮助,因为我对java不熟悉,现在花了几个小时在这方面,我很想完成它:) 这就是我到目前为止所做的:

import java.util.Scanner;  //Needed for the Scanner class
import java.util.Random;
import java.text.DecimalFormat;

public class CinemaPrice
{    
public static void main(String[] args)  //all the action happens here!    
{  Scanner input = new Scanner (System.in);

    int age = 0;
    double priceNumber = 0.00;


    Random generator = new Random();
    age = generator.nextInt(100) + 1;


    if ((age <= 5) || (age >=55) {
        priceNumber = 0.0;
    }else if (age <= 12){
        priceNumber = 12.50;
    }else {
        system.out.println("Sorry, But the age supplied was invalid.");
    }
    if (priceNumber <= 0.0) {
        System.out.println("The person age " + age + " is free!);
    }
    else {
        System.out.println("Price for the person age " + age + "is: $" + priceNumber);
    }
} //end of the main method 

} // end of the class

我不知道如何提示和读取用户的输入-你能帮忙吗


共 (2) 个答案

  1. # 1 楼答案

    我看到的第一个问题是,你需要在这里更新你的条件语句,因为13到54岁之间的任何东西都是无效年龄

    if ((age <= 5) || (age >=55) {
        priceNumber = 0.0;
    }else if (age <= 12){
        priceNumber = 12.50;
    }else if (age < 55){
       //whatever this ticket price is
    }else {
        system.out.println("Sorry, But the age supplied was invalid.");
    }
    

    像这样的东西会有用的

  2. # 2 楼答案

    您已经说过,真正的问题是将数据输入到程序中,下面应该演示如何使用Scanner类

    public static void main(String[] args) {
        System.out.println("Enter an age");
    
        Scanner scan=new Scanner(System.in);
    
        int age=scan.nextInt();
        System.out.println("Your age was " + age);
    
        double price=scan.nextDouble();
        System.out.println("Your price was " +  price);
    
    }
    

    这是最基本的想法,但是如果你提供了一个不正确的输入(比如一个单词),你可以得到一个例外,但是你可以检查你得到的输入是否正确,并且只在你想要的时候接受它,就像这样

    public class Main{
    
        public static void main(String[] args) {
            System.out.println("Enter an age");
    
            Scanner scan=new Scanner(System.in);
    
    
            while (!scan.hasNextInt()) { //ask if the scanner has "something we want"
                System.out.println("Invalid age");
                System.out.println("Enter an age");
                scan.next(); //it doesn't have what we want, demand annother
            }
            int age = scan.nextInt(); //we finally got what we wanted, use it
    
    
            System.out.println("Your age was " + age);
    
        }
    
    }