dfetter88
dfetter88

Reputation: 5391

Typing input in by hand works. Using input file causes infinite loop?

I'm currently working on a programming assignment for school. It's a simple text-based RPG. When I test the program locally (by hand), it works correctly. However, when I submit it to the grading server, it creates some sort of infinite loop.

I emailed my professor, who responded by explaining how the server tested the program. It uses the following format: java IPA1 (XML file name) < (Input file) > (output file). IPA1 is the name of the main java file. It seems that the < (Input file) is causing the endless loop for some reason... but I cannot pinpoint why.

My program gets its input with the following code:

boolean gameOver = false;
while (!gameOver) {
  Command cmd = inputParser.getCommand();
  gameOver = processCommand(cmd);
}

The getCommand(cmd) is as follows:

public Command getCommand() {
  String input = "";

  BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  try {
    input = reader.readLine();
  } catch(java.io.IOException exc) {
    System.out.println ("Error");
  }

  return new Command(input);
}

My question is: Why would this work when I type each command in sequentially by hand... but fail when an input file is used?

Upvotes: 2

Views: 186

Answers (2)

thejh
thejh

Reputation: 45568

This is because you are creating a buffered reader that reads more than you requested it to read. When you tell it to read five characters, it reads a lot more and saves them for the next request to boost performance. You should reuse one BufferedReader instead of creating many of them because when you create many of them, the first one already grabs stuff you want to read with the second one.

Upvotes: 5

Roman Goyenko
Roman Goyenko

Reputation: 7070

Try printing out what you read - there might be new line symbol at the end of the string or something is different about the file, so it doesn't exit from the loop. You can also debug the program to see exactly what's happening.

If you want exact answer to why in this case it doesn't work you need to post the processCommand() function and the content of the file.

Upvotes: 2

Related Questions