-3

我需要设计和实现一个名为 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

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

4

2 回答 2

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);

    }

}
于 2013-09-18T20:34:26.590 回答
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.");
}

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

于 2013-09-18T20:25:28.050 回答