输出继续运行

时间:2014-08-30 06:07:46

标签: java

为什么输出继续运行?当我运行这个程序,然后输入输出时,它会继续运行,并且不允许我输入任何更多的数字。为什么会这样?

import java.util.InputMismatchException;
import java.util.Scanner;

public class ExceptionTest2
{

    public static void main(String[] args)
    {
        Scanner st = new Scanner(System.in);
        int ab, bd, cde;
        ab = bd = cde = 0;
        boolean infinite, in;
        do
        {
            System.out.println("Enter the numbers to divide");
            infinite = false;
            in = true;
            try
            {
                ab = st.nextInt();
                bd = st.nextInt();
                infinite = false;
                in = true;
            }
            catch (InputMismatchException e)
            {
                System.out.println("Invalid input");
                in = true;
            }
            finally
            {
                if (in)
                {
                    try
                    {
                        System.out.println("I am in try block before exception");
                        cde = ab / bd;
                        System.out.println("I am in try block after exception");
                    }
                    catch (Exception e)
                    {
                        infinite = true;
                    }
                    finally
                    {
                        if (!infinite)
                        {
                            System.out.println("Answer is " + cde);
                        };
                    }
                }
            }
        }
        while (cde != 100);
        st.close();
    }
}

1 个答案:

答案 0 :(得分:1)

<强>问题:

ab = st.nextInt();

当你输入String时我不会被nextInt消耗掉,因此没有人会给你无限循环

<强>溶液

您需要使用在catch块中输入的那些字符以避免无限循环

<强>样品:

            catch (InputMismatchException e) {
               System.out.println("Invalid input");
               st.nextLine();
               in=true;
            }