2

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.