gpt4 book ai didi

Java:为什么程序会跳过字符输入?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:59:24 27 4
gpt4 key购买 nike

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com