2013-10-06 76 views
0

我正在學習Java並正在玩一些控制檯應用程序。我試圖驗證用戶輸入,並提示用戶在輸入錯誤時輸入另一個值。每當我輸入一個「空」值時,程序就會掛起,當我停下來時,它會吐出所有的錯誤。我怎樣才能真正檢查空?Java - 檢查用戶輸入的空白​​值是否失敗

例如:

do{ 
      //prompt user for word 
      System.out.print("\nType \"quit\" to exit \n"); 
      System.out.print("Enter a single word with no spaces: "); 

      //check to make sure user entered a valid string 
      if (in.hasNext()){ 
       strWord = in.next(); 
       int nWordLength = strWord.length(); 
       if(nWordLength > 0 && !strWord.isEmpty()){ 
        //do a whole bunch of stuff 
        // removed for brevity 
       }else{ 
       //alert user of invalid entry 
       System.out.println("Not a valid word."); 
      }else{ 
      //alert user of invalid entry 
      System.out.println("Not a valid word."); 
     } 
}while (!strWord.equals("quit")); //end if user enters quit 

System.out.println("You are now done with the program"); 

後,我殺了我的計劃,因爲它掛起,我得到像下面的輸出...

類型「退出」,退出 輸入不帶空格的字:不是一個有效的詞。

鍵入「退出」退出 輸入一個不含空格的單詞:不是有效的單詞。

鍵入「退出」退出 輸入一個不含空格的單詞:不是有效的單詞。

類型 「退出」,退出

進程退出代碼爲-1

回答

1

只是爲了簡化代碼

 boolean isValidInput = false; 
    do{ 
    //check to make sure user entered a valid string 
    strWord = in.nextLine(); 

    if(!(strWord.isEmpty()) && !(Character.isWhiteSpace(strWord.charAt(0)))) 
    { 
     isValidInput = true; 
     //whatever goes here 
    } 
    else 
     System.out.println("incorrect word entered"); 

    }while(!isValidInput); 
+0

這似乎爲字符串的工作,有沒有一種方法,使這項工作整數? – user797963

+0

如果它是'Scanner',那麼'nextInt()','nextDouble()'等將在那裏解救你 –

+0

@ user797963,因爲小孩子指出你會使用相應的方法來尋找你想要的任何一種輸入。 – Sello

0

完成我承擔inScanner

我認爲問題是你的代碼從來沒有看到來自用戶的輸入。

如果你更換hasNextLine()nextLine()所有來電hasNext()next()該緩衝區,並等待用戶按下回車鍵?