我在使用我創建的 Java 程式時感到困惑。
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
System.out.println("Your first input is " input1);
}
最初,當用戶Ctrl D在輸入程序中,它會及時結束程式并以這樣的形式顯示錯誤,
Your first input integer? ^D
Class transformation time: 0.0073103s for 244 classes or 2.9960245901639343E-5s per class
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651);
at Playground.Test1.main(Test1.java:13)
做一些研究我注意到Ctrl D終止排序的輸入。因此,我嘗試在我的代碼中添加幾行以防止錯誤再次出現,而是列印一個簡單 "Console has been terminated successfully!"且盡可能我的技能。
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
catch (NoSuchElementException e) {
System.out.println("Console has been terminated successfully!");
}
}
System.out.println("Your first input is " input1);
}
最后,我仍然得到同樣的錯誤。
uj5u.com熱心網友回復:
明白了!,代碼hasNext()將確保不會出現錯誤。此方法是檢查掃描儀的輸入中是否還有另一行,并檢查其是否已填充或為空。我還null用于在通過回圈后檢查我的陳述句,因此如果輸入值仍然存在null,同時保持Ctrl D.
public static void main(String[] args) {
Integer input1 = null;
System.out.println("Your first input integer? ");
Scanner scanner1 = new Scanner(System.in);
while(scanner1.hasNextLine()) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
break;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.println("Your first input integer? ");
}
}
if (input1 == null) {
System.out.println("Console has been terminated successfully!");
System.exit(0);
}
System.out.println(input1);
}
這個解決方案當然不是完美的,但如果有更簡單的選擇,我將不勝感激。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/481345.html
上一篇:在多執行緒和行程程式中捕獲例外
