使用Bluej打印数组时遇到问题

时间:2013-09-24 13:08:40

标签: java arrays bluej

我正在尝试打印一个分隔整数行的文件,我想在加载到数组后打印这些值,以便我可以处理和打印输出min,max,mean,median等。

以下是我的代码,但它只打印出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);
    }

1 个答案:

答案 0 :(得分:0)

每次输出2000作为输出的原因是因为您只打印出数组的整个长度,您在行this.data = new int[2000];中定义为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]);
}