0

Can someone explain why this is making an infinite loop? The hurcdata2 has about 30 straing values in it. I don't understand what the problem is.

import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Hurricanes2
{
public static void main(String[] args) throws IOException
{
    int i = 0;
    int hurricaneNumber = 0;
    String hurricanes = "";
    File fileName = new File("hurcdata2.txt");
    Scanner inFile = new Scanner(fileName);
    while (inFile.hasNext())
    {
        hurricaneNumber++;
    }
}
}
user1914491
  • 89
  • 1
  • 1
  • 7
  • 1
    I don't know anything about Java but it seems pretty obvious you need some code within your loop to move inFile on the the next item. Something like `inFile.nextLine();` after `hurricaneNumber++;` – Nick.Mc Dec 19 '12 at 22:45

2 Answers2

1

In your while - loop you should call inFile.nextLine() to make it process each line in the file.

  while (inFile.hasNext()) {
     hurricaneNumber++;
     String line = inFile.nextLine();
  }
nekman
  • 1,919
  • 2
  • 15
  • 26
1

As noted in the comment by @ElectricLlama you need to advance your file pointer, to get the next token, otherwise the hasNext() will always be true. Check this question and this tutorial on File I/O in Java.

Community
  • 1
  • 1
Khaled
  • 2,101
  • 1
  • 18
  • 26