-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

  • 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` would be a suitable structure for doing this, because it will enable you to check the existence of a command very efficiently. – Dawood ibn Kareem Apr 20 '22 at 18:58

1 Answers1

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) {
    ...
Rob Spoor
  • 6,186
  • 1
  • 19
  • 20