Java 程序捕获异常时跳过第一个字符输入?
System.out.println("Enter Character:");
f = s.next().charAt(0);
程序代码:
public class Main {
public static void main(String[] args) {
int num;
char f = 'y';
Scanner s = new Scanner(System.in);
do {
try {
System.out.print("Enter Number:");
num = s.nextInt();
catch (InputMismatchException e) {
System.out.println("False=> This is Not Integer");
}
System.out.println("Enter Character:");
f = s.next().charAt(0);
while(f != 'y' && f !='n') {
System.out.println("Press 'y' or 'n'");
f = s.next().charAt(0);
}
}
while(f == 'y');
System.out.print("Print:" + f);
}
}
编译器输出:
Enter Number:ghjgh
False=> This is Not Integer
Enter Character:(Compiler Skip This Input)
Press 'y' or 'n'
n
Print:n
为什么会这样。我不知道为什么,它会跳过异常捕获时的输入数据。
最佳答案
扫号后添加s.nextLine()
...
try {
System.out.print("Enter Number:");
num = s.nextInt();
}
catch (InputMismatchException e) {
System.out.println("False=> This is Not Integer");
}
s.nextLine();
...
关于Java:为什么程序会跳过字符输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30449491/