0

I'm trying to test a function that loops forever until QUIT is entered but I can't figure out how to simulate multiple lines of user input from system.

This is what I currently have

String validStartFlow = "START-FLOW\r\nQUIT\r\n";
ByteArrayInputStream in = new ByteArrayInputStream(validStartFlow.getBytes());
System.setIn(in);
CommandLineListener cmdLineListener = new CommandLineListener(eventBus,logger);
cmdLineListener.startCommandLineListener(in);

The method that loops forever is

while (!userCmd.equals("QUIT")) {
    userCmd = "";
    Scanner scanner = new Scanner(in);
    // BufferedReader reader = new BufferedReader(in);

    while (userCmd == null || userCmd.equals("")) {
        userCmd = scanner.nextLine();
    }

    ...
}

The START-FLOW is read in perfectly but then after that when it reaches scanner.nextLine() it crashes with the following error

No line found java.util.NoSuchElementException: No line found

How can I get it to read in QUIT from the validStartFlow string?

3
  • 1
    Did you try scanner.useDelimiter("\r\n")? Commented Oct 7, 2020 at 23:50
  • Just tried that and it's still failing for the same reason. Thanks for the input though I didn't think of that EDIT: Wait during debugging I noticed that it's actually skipping START-FLOW and going straight to quit when I call nextLine? Commented Oct 7, 2020 at 23:53
  • EDIT EDIT: It was because I was checking scanner.nextLine() in my debug console so in the code it was going straight to quit because start-flow was already read in. @DelfikPro you were totally right and my problem is solved. Thank you! Commented Oct 7, 2020 at 23:59

1 Answer 1

2

You create a new Scanner on every iteration and access nextLine() only once each.

Try extracting it from the loop:

Scanner scanner = new Scanner(in);
scanner.useDelimiter("\r\n");
String userCmd = "";

while (!userCmd.equals("QUIT")) {
        userCmd = scanner.nextLine();
...
Sign up to request clarification or add additional context in comments.

1 Comment

Good catch! I didn't notice that. But your previous comment of setting the delimiter solved it so ima do both. Thanks again my guy. If you edit this comment to have the set delimiter all set your question as solved

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.