繁体   English   中英

扫描仪异常处理

[英]Scanner exception handling

我正在尝试做一些简单的程序,但我对异常处理有点好奇。

因此,我的一段代码

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);

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

试试这个:-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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM