[英]Trouble with for loop continuing after catching an exception
嗨,我是java的新手,無法弄清楚這一點。 捕獲異常后,我希望for循環繼續並繼續讀取新的整數。 這是一項在線挑戰,希望您獲得5分(這表明之后應該期望輸入多少),
-150,
150000,
1500000000,
213333333333333333333333333333333333,
-100000000000000.
並轉換為以下輸出:
-150 can be fitted in:
* short
* int
* long
150000 can be fitted in:
* int
* long
1500000000 can be fitted in:
* int
* long
213333333333333333333333333333333333 can't be fitted anywhere.
-100000000000000 can be fitted in:
* long
我想讓計算機檢查一個字節,短,整數和長的數字是否不會太大。 它可以工作(也許不是最好的方式),直到達到213333333333333333333333333333333333333333。這會導致InputMismatchException(bc變大),並且代碼會捕獲它,但之后不起作用。 這是輸出:
-150 can be fitted in:
* short
* int
* long
150000 can be fitted in:
* int
* long
1500000000 can be fitted in:
* int
* long
0 can't be fitted anywhere.
0 can't be fitted anywhere.
我真的不知道有什么幫助將不勝感激!
public static void main(String[] args) {
int numofinput = 0;
Scanner scan = new Scanner(System.in);
numofinput = scan.nextInt();
int[] input;
input = new int[numofinput];
int i =0;
for(i = i; i < numofinput && scan.hasNext(); i++){
try {
input[i] = scan.nextInt();
System.out.println(input[i] + " can be fitted in:");
if(input[i] >=-127 && input[i] <=127){
System.out.println("* byte");
}if((input[i] >=-32768) && (input[i] <=32767)){
System.out.println("* short");
}if((input[i] >=-2147483648) && (input[i] <=2147483647)){
System.out.println("* int");
}if((input[i] >=-9223372036854775808L) && (input[i] <=9223372036854775807L)){
System.out.println("* long");
}
}catch (InputMismatchException e) {
System.out.println(input[i] + " can't be fitted anywhere.");
}
}
}
問題在於,異常發生后 ,不匹配的輸入在Scanner
仍無人認領,因此您將永遠在循環中捕獲相同的異常。
要解決此問題,您的程序需要從Scanner
刪除一些輸入,例如,通過在catch
塊中調用nextLine()
:
try {
...
} catch (InputMismatchException e) {
// Use scan.next() to remove data from the Scanner,
// and print it as part of error message:
System.out.println(scan.next() + " can't be fitted anywhere.");
}
input[]
數組可以替換為單個long input
,因為您從不使用先前迭代中的數據; 因此,無需將其存儲在數組中。
另外,您應該將對nextInt
的調用替換為對nextLong
的調用,否則您將無法正確處理大量數字。
你也應該刪除的條件為long
共
if((input[i] >=-9223372036854775808L) && (input[i] <=9223372036854775807L))
因為鑒於nextLong
讀取已成功完成,因此可以肯定是true
。
最后,應避免在程序中使用“幻數”,而應使用相應內置Java類中的預定義常量,例如
if((input[i] >= Integer.MIN_VALUE) && (input[i] <= Integer.MAX_VALUE))
代替
if((input[i] >=-2147483648) && (input[i] <=2147483647))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.