0

I am currently working on a program that examines each line in a text document, and does the same modifications to it. However, the for loop is only looping through once rather than the needed 5 times. Below is the portion of the code that is not working.

//I think this part is correct but I decided to include it just in case.
Scanner infile = null;
try {
    infile = new Scanner(new File("solution.txt"));
} catch(FileNotFoundException e) {
    System.out.println(e);
    System.exit(0);
}

for(int i = 0; i < 5; i++);
{
    s = infile.nextLine();
    System.out.println(s);
    System.out.println("LOOP"); //Just a debug test
}
infile.close();

The output of this code is the following:

define 88 as INT
LOOP

Whereas it should be:

define 88 as INT
LOOP
define 89 as INT
LOOP
define 90 as INT
LOOP
define 91 as INT
LOOP
define 92 as INT
LOOP
Michael Yaworski
  • 12,398
  • 17
  • 59
  • 91
Ripread
  • 170
  • 7

2 Answers2

3

Remove the semicolon:

for(int i = 0; i < 5; i++);

The code after is valid by itself, and so runs separately once.

{
    s = infile.nextLine();
    System.out.println(s);
    System.out.println("LOOP"); //Test system out
}
Community
  • 1
  • 1
bcorso
  • 40,568
  • 8
  • 56
  • 73
0

You need to remove ; at the end of for-loop.

The for-loop code you used

    for(int i = 0; i < 5; i++);
    {
        s = infile.nextLine();
        System.out.println(s);
        System.out.println("LOOP"); //Test system out
    }

is equal to the following code:

    for (int i = 0; i < 5; i++) {

    }
    s = infile.nextLine();
    System.out.println(s);
    System.out.println("LOOP"); // Test system out

That's why only the first one line content is read from the plain text file.

You'd better use infile.hasNext() to check if there is any content. Then read it. like

    while (infile.hasNext()) {
        s = infile.nextLine();
        System.out.println(s);
        System.out.println("LOOP"); // Test system out
    }
MouseLearnJava
  • 3,051
  • 1
  • 12
  • 20