2014-01-20 77 views
-1

我想阻止用戶提供空的輸入,這裏是我的代碼阻止Java的的readLine空輸入

private void guessWord(){ 
    String input = readLine("Your guess: "); 
    while(!isValidInput(input)){ 
     println("Your input is invalid, please try again."); 
     input = readLine("Your guess: "); 
    } 
    char letter = input.charAt(0); 
    letter = Character.toUpperCase(letter); 
    if(!(subtituteLetter(letter))){ 
     println("There are no " + letter + "\'s in the word."); 
     life -=1 ; 
    } 

} 

我不想空輸入傳遞給我的isValidInput,憑什麼我阻止readLine接受用戶的空輸入?

+3

你不能。只需在'isValidInput()'中檢查空白。 – Keppil

+0

你不能。你會......用你的方法檢查它。 –

回答

1

更換您while循環與這一個:

while(input.isEmpty() || !isValidInput(input)){ 
     println("Your input is invalid, please try again."); 
     input = readLine("Your guess: "); 
    } 
+0

我肯定會爲這個解決方案,更優雅,謝謝! – denisthamrin

+0

@ user3214407:如果您認爲它對您有幫助,請接受答案。閱讀本文以瞭解如何接受答案。 http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –

1

您可以簡單地強制用戶在循環中輸入非空字符串。

private void guessWord(){ 
    String input; 
    do{ 
    input = readLine("Your guess: "); 
    } 
    while(input.isEmpty()); 

    while(!isValidInput(input)){ 
     println("Your input is invalid, please try again."); 
     input = readLine("Your guess: "); 
    } 
    char letter = input.charAt(0); 
    letter = Character.toUpperCase(letter); 
    if(!(subtituteLetter(letter))){ 
     println("There are no " + letter + "\'s in the word."); 
     life -=1 ; 
    } 
} 
+0

感謝您的輸入! – denisthamrin