-2

I'm currently working on a project for my class in which I have to sort an array which is numbers in a text file. I have created a reader to see how many values I have in the .txt file so I can define my array size, but my while() statement seems to be broken and goes in a never ending loop when using .hasNextLine. Here is my code:

    File unsorted = new File("unsorted.txt");

    int j = 0;//Counter for the amount of slots in the array

    System.out.println("Executing file reading...");

    try
    {

        Scanner input = new Scanner(unsorted);

        while(input.hasNextLine()){

            j++;//Scanner to count the length of the array

            System.out.println(j);

        }

        input.close();

        System.out.println("The file has " + j + " lines.");

    }
    catch (IOException ex){

        System.out.printf("ERROR: Could not read file 'unsorted.txt'", ex);

    }

    System.out.println("File read.");

My print line after the try{} doesn't ever print, instead when I have the J print within the while() loop, it goes on forever. The file has 7 values inside of it for now, all numbers.

bordia
  • 49
  • 1
  • 8

1 Answers1

1

The value of the hasNextLine() method only changes -- only has the chance to change -- when you call nextLine(). The nextLine() method gives you the content of the line, and it advances the Scanner by one line.

Drew Wills
  • 8,408
  • 4
  • 29
  • 40