捕获exception后for循环继续出现问题
嗨,我是java的半新人,不能想出这个。 捕获exception后,我想要一个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
我希望计算机检查一个数字对于byte,short,int和long是否不大。 它工作(可能不是最好的方式)直到它达到213333333333333333333333333333333333。它导致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 =-127 && input[i] =-32768) && (input[i] =-2147483648) && (input[i] =-9223372036854775808L) && (input[i] <=9223372036854775807L)){ System.out.println("* long"); } }catch (InputMismatchException e) { System.out.println(input[i] + " can't be fitted anywhere."); } } }
问题是在exception之后 ,不匹配的输入在Scanner
仍然无人认领,因此您将永远在循环中捕获相同的exception。
要解决此问题,您的程序需要从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
替换,因为你从不使用先前迭代的数据; 因此,不需要将其存储在数组中。
此外,您应该通过调用nextLong
替换对nextInt
的调用,否则您将无法正确处理大数字。
你也应该完全删除这个条件
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))