2013-01-17 68 views
0

我是新來的Java。我希望代碼在用戶輸入錯誤的地方重複,而不是從頭開始。在「輸入b:」或「輸入c:」時,它回到開始「輸入a:」。我希望它只能重複使用,用戶輸入是a,b,c。提前致謝。while true try catch嵌套

public static void main(String[] args) 
{ 
Scanner sc = new Scanner(System.in); 
boolean itsANumber = true; 
while (itsANumber) 
{ 
    System.out.print("Enter a: "); 

    try 
    { 
    a = Double.parseDouble(sc.nextLine()); 

    System.out.print("Enter b: "); 
    try 
    { 
     b = Double.parseDouble(sc.nextLine()); 

     System.out.print("Enter c: "); 
     try 
     { 
     c = Double.parseDouble(sc.nextLine()); 
     if (a == 0) 
     { 
      aZero(); 
     } else 

     { 
      aNotZero(); 
     } 

     } catch (NumberFormatException nfe) 
     { 
     System.out 
      .println("That's not a number, please try again!"); 
     } 

    } catch (NumberFormatException nfe) 
    { 
     System.out 
      .println("That's not a number, please try again!"); 
    } 

    } catch (NumberFormatException nfe) 
    { 
    System.out.println("That's not a number, please try again!"); 
    } 
} 

} 
+7

異常處理不應該被用於控制邏輯流程。 – Renjith

回答

3

介紹一種方法,要求輸入一個數字並調用它三次。在該方法中,您將有while循環與try-catch

public static void main(String... args) { 
    Scanner sc = new Scanner(System.in); 
    double 
    a = askForDouble(sc, "a"), 
    b = askForDouble(sc, "b"), 
    c = askForDouble(sc, "c"); 
} 
static double askForDouble(Scanner sc, String varName) { 
    for (;/*ever*/;) { 
    System.out.format("Enter %s: ", varName); 
    System.out.flush(); 
    try { 
     return Double.parseDouble(sc.nextLine()); 
    } catch (NumberFormatExcetpion() { 
     System.out.println("That's not a number, please try again!"); 
    } 
    } 
} 
+0

感謝Marko的回答,你能模擬代碼嗎?我有點不明白如何去做。 –

0

您可以通過簡單的空檢查,如果你想如下嘗試,這是原始代碼,並且可能需要改變

Double a = null; 
Double b = null; 
Double c = null; 
Scanner sc = new Scanner(System.in); 
while(true){ 

    if(a != null){    
     System.out.println("Enter a :"); 
     a = readFromInStream(sc, "a"); 
      if(a == null) continue; 
    } 
    if(b != null){    
     System.out.println("Enter b :"); 
     b = readFromInStream(sc, "b"); 
      if(b == null) continue; 
    } 
    if(c != null){    
     System.out.println("Enter c :"); 
     c = readFromInStream(sc, "c"); 
      if(c == null) continue; 
    } 
    if(a != null && b != null && c != null){ 
     break; 
    } 
} 

private Double readFromInStream(Scanner sc, String varStr){ 
    Double temp = null; 
    try 
    { 
     temp = Double.parseDouble(sc.nextLine()); 
    }catch(NumberFormatException e){ 
     System.out.println("Invalid value for :"+varStr); 
    } 
    return temp; 
}