检查用户输入时出错

时间:2014-02-26 16:59:04

标签: java

我有一个班级询问用户他们想要什么类型的卡车。我需要知道一种方法来进行错误检查,这样如果他们输入“1”或“2”之外的东西,它会告诉他们这是一个无效的选项。

以下是代码:

public class InheritanceTUI {

    private int weight;
    private String flavors;
    private Scanner scan = new Scanner(System.in);
    private String truckType;


    public void run() {
        System.out.println("Type \"1\" if you want a generic truck" + "\n" + "Type \"2\" if you want an Ice Cream Truck");
        this.truckType = this.scan.nextLine();

        if (this.truckType.equals("1")) {
            System.out.println("You have chosen a generic truck!");
            System.out.println("Type in what weight (in pounds) you want your truck to be: ");
            String stringWeight = this.scan.nextLine();
            this.weight = Integer.parseInt(stringWeight);
            System.out.println("Your truck has a weight of " + this.weight + " pounds");
        }

        if (this.truckType.equals("2")) {
            System.out.println("You have chosen an Ice Cream Truck! " + this.truckType);
            System.out.println("Type in what weight (in pounds) that you want your ice cream truck to be: ");
            String stringWeight = this.scan.nextLine();
            this.weight = Integer.parseInt(stringWeight);
            System.out.println("You have entered a weight of " + this.weight + " pounds");
            System.out.println("What flavors do you want in your ice cream truck?");
            this.flavors = this.scan.nextLine();
            System.out.println("Your ice cream truck has a weight of " + this.weight + " pounds and contains " + this.flavors + " flavor(s)");
        }
    }
}

5 个答案:

答案 0 :(得分:2)

使用开关/案例,并处理默认分支中的无效选项

一些其他信息:您只能从Java SE 7打开字符串。直到Java SE 6,你可以例如使用Integer.parseInt(truckType)将您的String值转换为int并在之后进行切换

答案 1 :(得分:1)

检查开头的情况:

if (!"1".equals(truckType) && !"2".equals(truckType)) {
    // it's an invalid option, do something about it
}

答案 2 :(得分:1)

你可以使用开关盒。或者你应该在条件之后放置其他条件。

答案 3 :(得分:1)

if (this.truckType.equals("1")) {
       //Code
    }
  else if (this.truckType.equals("2")) {
       //Code
    }
else {
    System.out.println("Invalid option");
 }

答案 4 :(得分:0)

您最好的选择是使用开关盒