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 的原因是因为您只打印出数组的整个长度,您在 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]);
}
于 2013-09-24T13:25:37.390 回答