我有一個類,詢問用戶他們想要什麼類型的卡車。我需要知道一種方法來進行錯誤檢查,以便如果他們輸入除「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)");
}
}
}
你已經錯過了解釋問題 – Kick
請不要修改後消除了原來的問題,這可能是爲別人有用。只要接受最好的答案,並保持原樣。 –