當導入的文件包含100個或更多數字時,下面的代碼可用。如果文件中剩餘的數字少於100個,我該如何讓循環停止?當數字少於100時,由於數組未滿而出現錯誤。使用導入文件的Java循環
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();
}
如果讀取次數少於100次或讀取的最多100個整數時,您希望它停止? – ogzd
這兩個條件PLZ – user2052514