Sta*_*mir 3 java try-catch infinite do-while
当我尝试在循环中执行try-catch语句时遇到问题.我要求用户首先输入字母然后输入一个数字,如果他正确输入数字,程序结束.如果他输入字母而不是数字,程序应该说"发生错误请输入数字"并要求用户再次输入数字,但每次输入字母而不是数字时,程序进入无限循环,不允许我输入新值.然后去"发生错误你必须输入数字""请输入数字".
public class OmaBrisem {
public static void main(String[] args) {
Scanner tastatura = new Scanner(System.in);
boolean b = true;
int a = 0;
String r = "";
System.out.println("Please enter a letter");
r = tastatura.next();
do {
try {
System.out.println("Please enter numerical value");
a = tastatura.nextInt();
b = true;
} catch (Exception e) {
System.out.println("An error occured you must enter number");
b = false;
}
} while (!b);
}
}
Run Code Online (Sandbox Code Playgroud)
这是你的问题.如果用户在您希望输入数字的位置输入非数字,您nextInt()将引发异常,但不会从输入流中删除该字母!
这意味着当你循环回来再次获得该号码时,该信件仍将存在,你的nextInt()意志将再次引发异常.等等,无限制地(或者至少直到宇宙的热量死亡,或者机器最终崩溃,以先到者为准).
修复此问题的一种方法是在失败时实际读取/跳过下一个字符,nextInt()以便将其从输入流中删除.你基本上可以这样做,Scanner.findInLine(".")直到Scanner.hasNextInt()返回true.
以下代码显示了一种方法:
import java.util.Scanner;
public class MyTestProg {
public static void main(String [] args) {
Scanner inputScanner = new Scanner(System.in);
System.out.print("Enter letter, number: ");
// Get character, handling newlines as needed
String str = inputScanner.findInLine(".");
while (str == null) {
str = inputScanner.nextLine();
str = inputScanner.findInLine(".");
}
// Skip characters (incl. newline) until int available.
while (! inputScanner.hasNextInt()) {
String junk = inputScanner.findInLine(".");
if (junk == null) {
junk = inputScanner.nextLine();
}
System.out.println("Ignoring '" + junk + "'");
}
// Get integer and print both.
int num = inputScanner.nextInt();
System.out.println("Got '" + str + "' and " + num);
}
}
Run Code Online (Sandbox Code Playgroud)
以下成绩单显示了它的实际效果:
Enter letter, number: Abcde42
Ignoring 'b'
Ignoring 'c'
Ignoring 'd'
Ignoring 'e'
Got 'A' and 42
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |