用Java读取用户输入

时间:2013-09-18 20:16:20

标签: java

我需要设计并实现一个名为CinemaPrice的应用程序,以确定一个人付钱去看电影的费用。该程序应使用Random类生成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 个答案:

答案 0 :(得分:0)

我看到的第一个问题是你需要在这里更新你的条件声明,因为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.");
}

这样的东西会起作用......

答案 1 :(得分:0)

您已声明您的真正问题是将数据导入您的程序,以下内容应使用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);

    }

}
相关问题