扫描程序异常处理

时间:2017-06-09 06:05:43

标签: java

我试图做一些简单的程序,并且在异常处理方面我有一些小事情。

这是我的一段代码

do{
       System.out.println(helloWorld.line);

            System.out.print("Value a : ");
            try{
                if(scan.hasNextInt())
                    rep++;
                a = scan.nextInt();
            }
            catch (InputMismatchException e){
                rep = 0;
                scan.next();
                System.out.println("Input Mismatch, try again");
            }
            while (rep == 0);

然后是另一个代码

do{
       System.out.println(helloWorld.line);

            System.out.print("Value a : ");
            try{
                if(scan.hasNextInt())
                    rep++;
                a = scan.nextInt();
            }
            catch (InputMismatchException e){
                rep = 0;
                scan.next();
                JOptionPane.showMessageDialog(null,"Input 
                mismatch","Error",JOptionPane.INFORMATION_MESSAGE);
            }
            while(rep == 0);

我正在做一段代码来忽略错误的输入并做一个循环,直到扫描仪读取正确的输入也给出一个弹出消息。 问题是第一个代码按预期工作,第二个代码正在运行但在第一个输入后没有做任何事情并且程序没有终止。为什么呢?

1 个答案:

答案 0 :(得分:0)

试试这个: - scan.nextLine();这一行将清除缓冲区

do{
   System.out.println(helloWorld.line);

        System.out.print("Value a : ");
        try{
             scan.nextLine();
            if(scan.hasNextInt())
                rep++;
            a = scan.nextInt();
        }
        catch (InputMismatchException e){
            rep = 0;
            scan.next();
            JOptionPane.showMessageDialog(null,"Input 
            mismatch","Error",JOptionPane.INFORMATION_MESSAGE);
        }
        while(rep == 0);

了解更多信息:https://itaehun.wordpress.com/2010/09/30/flush-in-java-when-using-nextline/

相关问题