我對代碼中的catch語句之後做了些什麼感到困惑。在循環中引發異常並捕獲後,循環變得無限。我還發現,輸入一個非常長的序列(+10左右)的數字將導致循環無限。我在java中的異常處理方面相當新,所以詳細描述會非常有教育意義。在捕獲異常後怎麼辦困惑
public static void main(String[] args)
{
boolean cont = false;
while (!cont)
{
addInputNumber();
cont = tryAgain();
}
}
private static void addInputNumber()
{
boolean valid;
int total;
int inputInt;
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
do
{
try
{
System.out.print("Enter a number(between 0 and 1000)");
inputInt = input.nextInt();
if(inputInt > 0 && inputInt < 1000)
{
valid = true;
total = (inputInt % 10) + ((inputInt/10) % 10) + (inputInt/100);
System.out.println("\n" + "The total of " + inputInt + " is " + total);
}
else
{
System.out.println("\n" + "ERROR---ENTER A NUMBER BETWEEN 0 AND 1000" + "\n");
valid = false;
}
}
catch(InputMismatchException ex)
{
System.out.println("\n" + "ERROR---ENTER A NUMBER BETWEEN 0 AND 1000" + "\n");
valid = false;
}
} while(!valid);
}
在捕獲塊中將有效更改爲true。 – Veera