gpt4 book ai didi

java - 将整数存储在数组中后打印文件中的整数数量?

转载 作者:行者123 更新时间:2023-12-01 11:11:18 27 4
gpt4 key购买 nike

我必须将文件中的所有整数存储到一个数组中,然后打印该数组和文件中的整数数量。

这里是在数组中存储整数的方法。它工作正常,因为我的第二个方法中的输出正确打印了 index = i, element = array[i]

public static Integer [ ] returnFileIntegers(String filename) {
int i = 0;
int x = 0;
Integer [ ] array = new Integer[10000]; //instantiate array of 10000 integers
if(filename.length() == 0){
System.out.println("Please enter the file name as the 1st commandline argument.");
}
else { //attempt connect and read file
File file = new File(filename);
Scanner inputFromFile = null;
try {
inputFromFile = new Scanner(file);
}
catch (FileNotFoundException fnfe) {
System.out.print("ERROR: File not found for \"");
System.out.println(filename+"\"");
}
//if made connection to file, read file
if(inputFromFile != null){
System.out.print("Reading from file \"" + filename + "\":\n");
//loop and print to check if file connected

//read next integer and store into array
while (inputFromFile.hasNextLine()) {
try {
x = inputFromFile.nextInt();
array[i] = x;
i++;
System.out.println(x);

}
catch (InputMismatchException ime) {
inputFromFile.next();
}
catch (NoSuchElementException nsee) {
}
}
}
}
return array;
}

这是我用来打印数组和整数数量的方法。我知道这是错误的,因为我正在打印 array.length 但我不知道应该使用什么来使其打印 整数数量 而不是 数组长度

  public static void printArrayIndexInteger(Integer [ ] array, String filename) {
//print number of integer in file
System.out.println("Number of integers in file \"" + filename + "\" = " + array.length);
//print array index and elements
for(int i=0;i<array.length;i++) {
if(array[i] != null){
System.out.print("\nindex = " + i + ", ");
System.out.print("element = " + array[i]);
}
}
}

这是当前输出的样子:

Number of integers in file "groceries.csv" = 10000

index = 0, element = 3
index = 1, element = 12
index = 2, element = 1
index = 3, element = 1
index = 4, element = 5
index = 5, element = 1

它应该是什么:

Number of integers in file "groceries.csv" = 6

index = 0, element = 3
index = 1, element = 12
index = 2, element = 1
index = 3, element = 1
index = 4, element = 5
index = 5, element = 1

如何获得打印数组中元素数量而不是数组长度的方法?

最佳答案

它说 10000 因为这就是你声明它的方式:

整数[]数组=新整数[10000]

这些额外的索引仍然存在,并且默认值为 null。数组长度等于数组中元素的数量。如果您事先不知道大小,请考虑使用大小可以调整的 ArrayList

了解数组中有多少数字的唯一方法是循环遍历数组并进行计数,但是 ArrayList 比为数组分配任意大的长度是更好的解决方案。

关于java - 将整数存储在数组中后打印文件中的整数数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32335188/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com