当导入的文件包含 100 个或更多数字时,我的以下代码有效。如果文件中剩余的数字少于 100 个,如何让循环停止?当数字少于 100 个时,由于数组未满而出现错误。
try {
Scanner in = new Scanner(new File(filename));
int[] aNums = new int[100];
System.out.print("Array contents: ");
int i =0;
while (i < aNums.length){
generated = in.nextInt() ;
aNums[i] = generated;
System.out.print( aNums[i] );
System.out.print(" ");
i++;
}
System.out.println(" ");
System.out.println(" ");
System.out.print("Array contents: ");
for (i = aNums.length - 1; i >= 0; i--) {
System.out.print( aNums[i] );
System.out.print(" ");
}
}
// Catch block, needed when using file input
catch (FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}