2016-01-22 33 views
1

我目前正在研究一個Java程序,該程序會在命令行上運行基本的配置文件編輯器。 我有1個問題...有些條目必須是有效的輸出。 我嘗試使用如何強制Scanner.next()輸出一個值?

while(!scanner.hasNext()){ 
    System.err.println("Invalid Value"); 
} 
String str = scanner.next(); 

在我看來這應該工作,因爲每次scanner.hasNext();被稱爲程序應暫停,直到在控制檯中輸入內容。 但是,當我運行程序(輸入無效值)它只是保持循環循環。 我做錯了什麼或者這只是一個錯誤? 感謝您的幫助!

+1

你是說你得到「無效值」無限次被淹,因爲它是在while循環? – Gendarme

+1

如果'scanner.hasNext()'返回false,則表示您已到達流的末尾並多次調用它將無濟於事。 –

+0

@Gendarme基本上是的 – RoiEX

回答

1

爲了完整這裏的目的是一個快速的解決方案,採用while (true) -approach:

public static void main(String[] args) { 
    String input = null; 
    try (Scanner scanner = new Scanner(System.in)) { 
     while (true) { 
      System.out.println("Please enter SOME INFORMATION:"); 
      if (scanner.hasNextLine()) { 
       input = scanner.nextLine(); 
       if (inputIsSane(input)) break; 
       System.out.println("Your input is malformed. Please try again."); 
      } 
     } 
    } 
    System.out.println("Got valid input. Input was: " + input); 
    // continue with the rest of your program here 
} 

private static boolean inputIsSane(String input) { 
    // replace with your actual validation routine 
    return input.equals("let me pass"); 
}