-1

I need to type a command twice into the Console, only then it recongnizes it as a input. I tried as the reader from the command file also a scanner instead of a bufferedReader. I hope you can help me!

private File commandFile = new File("commands.txt");

public void run() {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    while(true) {
        try {
            if(in.readLine() != null) {
                String input = in.readLine();
                if(commandExists(input) == true) {
                    System.out.println("Command exists");
                }else LogManager.writeLog("Cannot find Command " + input);
            }
        } catch (IOException e) {
            LogManager.writeLog("[InputScanner] Cannot read Console Input!");
            System.err.println(e.getCause());
        }
    }
}

private boolean commandExists(String command) {
    Boolean result = false;
    if(!commandFile.exists()) {
        LogManager.writeLog("[InputScanner] Cannot Find Commands File!");
    }
    try {
        BufferedReader reader = new BufferedReader(new FileReader(commandFile));
          String line;
          while (null != (line = reader.readLine())) {
              if(line.equalsIgnoreCase(command)) {
                  result = true;
              }
          }
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    return result;
}

This is the code from the commands.txt file:

Code command.txt file

1
  • Be aware that you're reading the entire command file for every line of the console input. It would be better if you read it just once, and stored the commands in memory. Maybe a HashSet<String> would be a suitable structure for doing this, because it will enable you to check the existence of a command very efficiently. Commented Apr 20, 2022 at 18:58

1 Answer 1

1
if(in.readLine() != null) {
    String input = in.readLine();

Those are two reads. The first consumes the first part, but you don't use it other than for the nullcheck.

Fix:

String input = in.readLine();
if (input != null) {
    ...
Sign up to request clarification or add additional context in comments.

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.