2014-02-10 51 views
0

我有以下幾點:我很清楚,我有一個例外,我必須捕捉如果輸入輸入不是數字,什麼讓我發瘋只是第一次運行通過這個功能正如預期的那樣直到這一點。當我要求用戶輸入自己的體重時,它會進入while(!isNum)的無限循環。我會想到關閉掃描儀,並在第二次運行時重新創建該對象將創建一個停止點,允許用戶輸入數據,因爲它會執行一個。我正在利用IDE和Java的新開發者Eclipse Kepler,將其與C#作爲初學者進行比較。一些指導將不勝感激。無限循環第二次使用掃描儀

import java.text.NumberFormat; 
import java.util.InputMismatchException; 
import java.util.Locale; 
import java.util.Scanner; 
import java.util.regex.MatchResult; 

import org.omg.CORBA.DynAnyPackage.TypeMismatch; 

public class TheValidator { 

private int height; 
private int weight; 
private boolean isNotValid = true; 
private boolean weightIsValid = false; 
private Scanner sc; 

void inputTest(){ 
    while (!isNotValid);{ 
     System.out.print("Please enter your height in inches."); 
     numTest(); 
    } 
    isNotValid = true; 
    while (!isNotValid);{ 
     System.out.print("Please enter your weight in inches."); 
     numTest(); 
    } 
    sc.close(); 
} 


void numTest() 
{ 
    // Variable to see if entered data is legit number. 
    while(isNotValid) 
    { 
     boolean isNum = false; 
     boolean isPos = false; 
     int num = 0; 

     while(!isNum) 
     { 
      if(sc.hasNextInt()) 
      { 
       isNum = true; 
       num = sc.nextInt(); 
       if(num > 0) 
       { 
        isPos = true; 
       } 
       else 
       { 
        System.out.println("You entered a number that is not positive. Please ensure you entered a positive numeric number and try again."); 
       }      
      } 
      else 
      { 
       System.out.println("What you entered isn't even a number. Please ensure you entered a positive numeric number and try again."); 
      }   
     } 
     if(isNum && isPos) 
     { 
      isNotValid = false; 
     } 
    } 
} 
} 

回答

0

的第一個問題是,如果hasNextInt()是假的,你需要做一些事來報復掃描器過去的非法輸入。如果你不這樣做,掃描儀的光標(指向要查看的下一個輸入)將始終保持在同一個地方,導致無限循環。如果執行此,當hasNextInt()是假的:

sc.nextLine(); 

,將沖洗出來就行一切,允許用戶鍵入新的輸入。

這個修復是不夠的;當我添加這個時,我得到了其他例外情況,我認爲這與您爲每條輸入行打開一個新的Scanner這一事實有關。這不應該是必要的。當創建TheValidator時,您可以將sc初始化爲新的Scanner;並且您可能需要將close方法添加到關閉掃描儀的TheValidator

+0

我想我對[nextLine()](http://www.tutorialspoint.com/java/util/scanner_nextline.htm)實際做了什麼的措辭有些困惑。它討論了這種方法「使掃描儀超越當前行並返回被跳過的輸入」。我想我有點困惑。我成功地爲上述內容做了一些修改。對你來說,如果我正確理解這一點,ajb nextLine()確實有點像復位。我想我需要hasNextInt(),因爲它是我用來驗證輸入內容實際上是數字的。欣賞指針 – TargetofGravity

+0

@TargetofGravity'nextLine()'確實會返回被跳過的輸入,所以如果你願意,你可以說'String line = sc.nextLine()'。有很多用途您想要檢索該行的其餘部分並使用它。在這裏,我沒有給結果分配任何東西,這意味着我們只是拋出它,但我們真正想要的只是跳過當前行的效果(並因此強迫用戶在我們要求掃描儀時輸入另一行更多數據)。 – ajb