1

I have a file that has a different integer on each line. for example:

5
4
3
2
1

I am trying to write a program to run through each int, and put that int into an array. So far, my code is:

      Scanner sc = new Scanner(args[0]);

      BufferedReader reader = new BufferedReader(new FileReader(args[0]));
      lines = 0;
      while (reader.readLine() != null) lines++;
      reader.close();

      intArray = new int[lines];

      int counter = 0;
      while(sc.hasNextInt()) {
        intArray[counter] =sc.nextInt();
        counter++;
      }

My program creates the array with the right number of indices, but it is never going into the while loop for the scanner. I have no idea why this is, as it looks like I have the same code according to this page.

Community
  • 1
  • 1
Ctech45
  • 496
  • 9
  • 17

1 Answers1

3

Unless your file path is space separated numbers, you won't get any numbers. The Scanner was scanning the file path (as a String), not the file.

Scanner sc = new Scanner(new FileInputStream(args[0]));

And FYI, it would be more clear if you used a List rather than reading the file twice.

Paul Draper
  • 78,542
  • 46
  • 206
  • 285