[英]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.