每次输出 2000 的原因是因为您只打印出数组的整个长度,您在 line 中将其定义为 2000 this.data = new int[2000];
。要打印出数组中值的数量,最简单的方法就是使用count
,因为它已经保存了该数字。要打印出数组中的所有值,只需循环遍历数组直到最后一个值,打印每个值。代码示例如下:
String txt = UIFileChooser.open();
this.data = new int[2000];
int count = 0;
try {
Scanner scan = new Scanner(new File(txt));
while (scan.hasNextInt() && count < data.length){
this.data[count] = scan.nextInt();
count++;
}
scan.close();
}
catch (IOException e) {
UI.println("Error");
}
// this line will print the length of the array,
// which will always be 2000 because of line 2
UI.printf("Count: %d\n", this.data.length);
// this line will print how many values are in the array
UI.printf("Values in array: %d\n", count);
// now to print out all the values in the array
for (int i = 0; i < count; i++) {
UI.printf("Value: %d\n", this.data[i]);
}
// you can use the length of the array to loop as well
// but if count < this.data.length, then everything
// after the final value will be all 0s
for (int i = 0; i < this.data.length; i++) {
UI.printf("Value: %d\n", this.data[i]);
}