0

整数の行で区切られたファイルを印刷しようとしています。最小、最大、平均、中央値などを処理して印刷できるように、配列にロードした後に値を印刷したいと考えています。

以下は私のコードですが、印刷するだけ2000です:

   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");
    }
     {UI.printf("Count:  %d\n", this.data.length);
    }
4

1 に答える 1

0

毎回出力として 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]);
}
于 2013-09-24T13:25:37.390 に答える