java中的nextLine函數

今天在學習java異常處理的時候,下面這段程序中的nextLine()的用法怎麼也看不明白。初學者看到這段代碼會誤以為程序中的input.nextLine()這句是多餘的。其實,不使用這句的話,如果輸入不是整數,程序會陷入死循環。

當你不加input.nextLine()時,你輸入小數,try塊中給input.nextInt()就無法執行,因為小數無法被讀取,我猜是小數一直留在鍵盤緩衝區。這時continueInput = false沒有執行,程序直接跳到catch塊中,執行了輸出語句之後,開始循環的下一次執行。第二次循環時,因為上次輸入的小數依然在鍵盤緩衝區內,input.nextInt()直接從鍵盤緩衝區得到整數失敗,你連輸入的機會都沒有了,直接跳到catch,後面的執行就與第一次一樣。如此,程序就陷入了死循環。

如果你加入input.nextLine(),緩衝區的小數就能被讀取走,下次就能正常鍵盤輸入了,就不會出現死循環的問題了。

<code>import java.util.InputMismatchException;
import java.util.Scanner;

public class nextLineDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("enter an integer");
int number = input.nextInt();

System.out.println("the number entered is" + number);
continueInput = false;
} catch (InputMismatchException e) {
System.out.println("try again, incorrect input");
input.nextLine();
}
}while(continueInput);
}
}/<code>

來源:https://www.tuicool.com/articles/7nYr2mn

java中的nextLine函數


分享到:


相關文章: