将它们存储在数组中后打印文件中的整数?

时间:2015-09-01 15:13:56

标签: java arrays file io

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

这是在数组中存储整数的方法。它工作正常,因为我的第二个方法中的输出正确打印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

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

2 个答案:

答案 0 :(得分:1)

它说10000,因为你是如何宣称的:

Integer[] array = new Integer[10000]

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

知道数组中有多少个数字的唯一方法是循环遍历并计数,但ArrayList比将数组赋值任意大的长度更好。

答案 1 :(得分:0)

您应该使用ArrayList:

ArrayList<Integer> array = new ArrayList<>();

另外,替换添加

array[i] = x;
i++;

使用:

array.add(x);

自动(联合)装箱使int可分配给整数。 最后替换

return array;

使用

return array.toArray(new Integer[array.size()]);