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

标签 java exception-handling

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/

相关文章:

c# - 在 C# 4.0 中使用依赖注入(inject)时处理异常

c# - 在没有 Wait() 的情况下使用 TPL 处理异常

java - setMapoutputkeyclass和setMapoutputvalueclass方法

java - 绘制透明圆圈填充在外面

java - Lombok 的自定义 Setter 和 Getter

java - 如何使用 Spring jdbc 模板(jdbcTemplate 或 namedParameterJDBCTem)从数据库中检索值

c# - 抛接逻辑

c++ - GCC 程序不捕获异常

ajax - Ajax调用中的异常处理

java - 自定义绘画 JPanel 偏移绘图