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

时间:2015-05-26 04:30:27

标签: 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

为什么会发生这种情况。我不知道为什么,它会跳过异常捕获的输入数据。

2 个答案:

答案 0 :(得分:1)

扫描号码后添加s.nextLine()

...
try {
    System.out.print("Enter Number:");
    num = s.nextInt();
}
catch (InputMismatchException e) {
    System.out.println("False=> This is Not Integer");
}
s.nextLine();
...

答案 1 :(得分:0)

您可以使用instanceof关键字,也是这样的:

try{
    String input = s.nextInt();
    int num = Integer.parseInt(input);
    // if execute here input is number
}catch(Exception e){
    // if execute here input is not number
    System.out.println("Please input number!");
}