为什么输出继续运行?当我运行这个程序,然后输入输出时,它会继续运行,并且不允许我输入任何更多的数字。为什么会这样?
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();
}
}
答案 0 :(得分:1)
<强>问题:强>
ab = st.nextInt();
当你输入String
时我不会被nextInt
消耗掉,因此没有人会给你无限循环
<强>溶液强>
您需要使用在catch块中输入的那些字符以避免无限循环
<强>样品:强>
catch (InputMismatchException e) {
System.out.println("Invalid input");
st.nextLine();
in=true;
}