2014-02-26 83 views
-2

我有一個類,詢問用戶他們想要什麼類型的卡車。我需要知道一種方法來進行錯誤檢查,以便如果他們輸入除「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)"); 
     } 
    } 
} 
+0

你已經錯過了解釋問題 – Kick

+0

請不要修改後消除了原來的問題,這可能是爲別人有用。只要接受最好的答案,並保持原樣。 –

回答

1

檢查開頭的條件:

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

謝謝,奧斯卡// – WhoYou

2

使用開關/箱,以及如何在默認分支

一些額外的選項無效信息:您只能從Java SE 7切換字符串。直到Java SE 6,你可以例如使用Integer.parseInt(truckType)將您的字符串值轉換爲int,然後執行開關操作。

1

您可以使用switch case進行此操作。或者你應該在條件之後放置其他條件。

0

你最好的選擇是使用一個開關的情況下

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