毎回出力として 2000 を取得する理由は、行で 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]);
}