2013-04-07 56 views
0

只是有點困惑,這裏發生了什麼。例如,該錯誤陷阱的重點在於用戶輸入3個數字/字母而不是4位數字。這個錯誤陷阱的設計循環直到用戶正確的問題。但是它會循環顯示錯誤消息。任何人都可以提供一些關於發生什麼的指針?錯誤捕獲幫助;消息不斷重複

JFrame Error = new JFrame(); 

String input = JOptionPane.showInputDialog(null,"Enter the 4 digit resistor values:"); 

while (true){ 
    try{ 

    int numInput = Integer.parseInt (input); 

    if (numInput >= 1000) { 
    break; 
    } 
    else { 
     JOptionPane.showMessageDialog(Error,"Invalid Input."); 
    } 
    } 
    catch (Exception e){ 
    JOptionPane.showMessageDialog(Error,"Invalid Input."); 

    } 
} 
+1

要求輸入的行不在循環中。 – 2013-04-07 03:12:59

回答

0

您需要將代碼輸入到循環中。

JFrame Error = new JFrame(); 

String input = null; 

while (true){ 
    try{ 

    input = JOptionPane.showInputDialog(null,"Enter the 4 digit resistor values:"); 
    int numInput = Integer.parseInt (input); 

    if (numInput >= 1000) { 
    break; 
    } 
    else { 
     JOptionPane.showMessageDialog(Error,"Invalid Input."); 
    } 
    } 
    catch (Exception e){ 
    JOptionPane.showMessageDialog(Error,"Invalid Input."); 

    } 
} 
-1

你要問一個新的價值,循環。將其更改爲:

String input; 

try { 
    while (true){ 
     input = JOptionPane.showInputDialog(null,"Enter the 4 digit resistor values:"); 

     int numInput = Integer.parseInt (input); 

     if (numInput >= 1000) { 
      break; 
     } 
     else { 
      JOptionPane.showMessageDialog(Error,"Invalid Input."); 
     } 
    } 
} catch (Exception e) { 
    JOptionPane.showMessageDialog(Error,"Invalid Input."); 
} 
+1

如何不需要嘗試捕捉?如果用戶輸入abcd(這種類型的輸入*在問題中被解決了)怎麼辦? – chris 2013-04-07 03:15:04

+0

@chris哦,會解決這個問題。 – Mordechai 2013-04-07 03:29:57

0

正如JacobM所提到的,您需要在while循環內請求輸入。當catch子句終止時,代碼的下一件事將是while循環中的第一件事。

JFrame Error = new JFrame(); 

while (true){ 
    String input = JOptionPane.showInputDialog(null,"Enter the 4 digit resistor values:"); 
    try{ 

    int numInput = Integer.parseInt (input); 

    if (numInput >= 1000) { 
    break; 
    } 
    else { 
     JOptionPane.showMessageDialog(Error,"Invalid Input."); 
    } 
    } 
    catch (Exception e){ 
    JOptionPane.showMessageDialog(Error,"Invalid Input."); 

    } 
}