Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

console application - Java BufferedReader on System.in ignores first line / command

I have created a simple console application for java with an JavaBufferedReader to read the commands from the terminal. For some reason the first command issued is always completly ignored. Even while debugging no value gets read and the input String is still not initialized. After issueing a second command the input String gets the value I wrote in the console.

I am using IntelliJ and the integrated terminal with gradle and JDK 11. I litterly can't see any reason, why the first command is just completly ignored.

BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));

And the main shell functionality

 public void runMainLoop() throws IOException {
    boolean quit = false;

    while (!quit) {
      System.out.print("prompt> ");
      final String input = inReader.readLine();   // <-- This input gets no value after pressing "enter". 
      if (input == null) {                        // all other "enter" after the first one are working
        break; 
      }

      try (final Scanner scanner = new Scanner(input)) {
        scanner.useDelimiter("\s+");

        if (!scanner.hasNext()) {
          printError("No command specified!");
          break;
        }

        switch (scanner.next().toLowerCase()) {

          case "help":
            printHelpMessage();
            break;

          case "quit":
            quit = true;
            println("Terminate...");
            break;

          default:
            printError("Unknown command given.");
            printHelpMessage();
            break;
        }
      }
    }
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suggest to apply the divide & conquer debugging strategy: Start with the absolute minimum that works and add parts of the program back until it stops working. Then examine the last added part.

This works for me, so I guess your problem is somewhere else:

BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));
String input = inReader.readLine();
System.out.println(input);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...