简体   繁体   English

使用Bluej无法打印阵列

[英]Trouble printing an array using Bluej

I'm trying to print a file which is separated lines of integers and I want to print the values after loading into an Array, so that I can process and printout the min, max, mean, median, etc. 我正在尝试打印一个由整数分隔的行的文件,我想在加载到数组中后打印值,以便可以处理和打印最小值,最大值,均值,中位数等。

Here is my code below, but it only prints out 2000 : 这是我的以下代码,但仅打印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);
    }

The reason you are getting 2000 as your output every time is because you are only printing out the entire length of the array, which you define as 2000 in the line this.data = new int[2000]; 每次获得2000作为输出的原因是,您仅打印出了数组的整个长度,您可以在this.data = new int[2000];行中将其定义为2000 this.data = new int[2000]; . To print out the number of values in the array, the simplest way would just be to use count , because it already holds that number. 要打印出数组中值的数量,最简单的方法就是使用count ,因为它已经保存了该数量。 To print out all the values in the array, simply loop through the array up to the last value, printing each one. 要打印出数组中的所有值,只需遍历数组直到最后一个值,然后打印每个值。 Code examples are below: 代码示例如下:

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]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM