[英]I am Facing issues in Scanner Class in java
如果我輸入了錯誤的輸入(例如,如果我輸入String而不是Integer),則循環未結束,則下次將無法獲得輸入。 我在這里(下)附上整個程序。 你能幫忙嗎? 提前致謝!!!
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* If we enter the wrong input(example , if we enter sting instead of integer) it goes unending loop
*
* @author Nithish
*
*/
public class Sample2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 1; i++) {
try {
System.out.println("Enter the value");
int obj = scanner.nextInt();
System.out.println(obj);
} catch (InputMismatchException e) {
i--;
e.printStackTrace();
}
}
}
}
在InputMismatchException上,您正在執行i--,因此修改了循環條件以防止沒有所需輸入的情況下循環結束。 如果您閱讀Scanner.nextInt()的API文檔,則應注意以下幾點:
如果翻譯成功,則掃描程序將前進經過匹配的輸入。
這意味着如果輸入不能轉換為int,則掃描儀不會前進。 因此,在下次調用nextInt()時,它將重新讀取完全相同的非整數輸入,並再次失敗。 在嘗試再次獲取int之前,您需要閱讀該非整數標記。
同樣,不要弄亂循環內部的循環索引,因為這可能會引起問題。 取而代之的是使用while循環,此循環從現在開始的3個月更加干凈,調試起來也更加容易:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Sample2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean done = false;
int result = 0;
while (!done) {
try {
System.out.print("Enter the value: ");
String temp = scanner.nextLine();
result = Integer.parseInt(temp);
done = true;
} catch (NumberFormatException e) {
System.out.println("Please only enter integer data");
}
}
scanner.close();
}
}
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
try {
System.out.println("Enter the value");
int obj = scanner.nextInt();
System.out.println(obj);
} catch (InputMismatchException e) {
i--;
//e.printStackTrace();
scanner.nextLine(); //you can add this here.
//scanner.next(); you can also use this
}
}
那下面呢?
Scanner sc = new Scanner(System.in);
while (!sc.hasNext()) {
System.out.println("Enter the value");
if (src.hasNextInt()) {
i = src.nextInt();
System.out.println("Thank you! (" + i+ ")");
}
else
{
System.out.println("Please only int");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.