Console only recognizes second input Java

46 views Asked by At

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

There are 1 answers

0
Rob Spoor On
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) {
    ...