Java 使用Bluej打印阵列时出现问题
我试图打印一个由整数行分隔的文件,我想在加载到数组后打印值,这样我就可以处理并打印出最小值、最大值、平均值、中值等 下面是我的代码,但它只打印出Java 使用Bluej打印阵列时出现问题,java,arrays,bluej,Java,Arrays,Bluej,我试图打印一个由整数行分隔的文件,我想在加载到数组后打印值,这样我就可以处理并打印出最小值、最大值、平均值、中值等 下面是我的代码,但它只打印出2000: String txt = UIFileChooser.open(); this.data = new int[2000]; int count = 0; try { Scanner scan = new Scanner(new File(txt)); while (scan.has
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);
}
String txt=UIFileChooser.open();
this.data=新整数[2000];
整数计数=0;
试一试{
扫描仪扫描=新扫描仪(新文件(txt));
而(scan.hasnetint()&&count每次输出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]);
}
String txt=UIFileChooser.open();
this.data=新整数[2000];
整数计数=0;
试一试{
扫描仪扫描=新扫描仪(新文件(txt));
while(scan.hasNextInt()&&count
您正在打印数组的长度,您在行中定义为2000;
this.data=new int[2000];您是在打印数组中的值,还是打印值的数量?是的,我正在尝试打印数组中的值的长度,但我几乎无法计算出来,因为我总是得到“2000”或者终端错误如果我仍然在printf中使用this.data.length,但data.length作为计数,那会怎么样?我的意思是使用data.length逐行扫描数据,就像计数一样,因为UI.printf(“总大小:%d\n”,this.data.length);是私有的,因为我无法更改“大学代码”.count工作得非常好。我编辑了我的答案,以了解您在评论中提出的问题。您可以使用循环中数组的长度而不是count,但是如果您读入的文件中没有2000个数字,那么这些数字之后的所有内容都将是0