Search code examples
javajava.util.scanneruser-input

How to make it so my program doesn't ask for input twice?


I'm using the Scanner class in Java and I ran into an issue where my program would do something like this:

public static void answer() {
    System.out.print("\t> ");
    command = scan.nextLine(); // It needs to be able to read the full line to be able to capture spaces
}

public static void main(String[] args) {
    while (!command.contains("Hello World!")) {
        System.out.println("Hello!!");
        answer();
    }
}

But would print this:

Hello!!
    > Hello!!
(user input)

So, after some research, I decided to change my program to be something like this:

public static void answer() {
    scan.nextLine(); // new piece
    System.out.print("\t> ");
    command = scan.nextLine();
}

public static void main(String[] args) {
    while (!command.contains("Hello World!")) {
        System.out.println("Hello!!");
        answer();
    }
}

This led to a different problem. If the user messes up their input by typing something like "fjbejwkb" instead of "Hello World!", this would happen:

Hello!!
    > fjbejwkb (user inputs wrong thing)
Hello!!
(user input)
    > (user input)

If I get rid of my added scan.nextLine(), I return to my original problem of "Hello!!" being printed twice but if I leave it, whenever I use the answer() method after its first use it will force the user to type in two things. While the first isn't read, I'm sure this could lead to some confusion which I'd like to avoid.

I've tried using println / \n instead of scan.nextLine() but this is visually unappealing to me:

Hello!!

    > (user input) 

I've also tried command = scan.next() instead of command = scan.nextLine() but this does not capture spaces - which for the problem I'm working on I need.

Here's what I want:

Hello!!
    > fjbejwkb (user inputs wrong thing)
Hello!!
    > (user input)

When the user inputs the wrong thing, it should ask for input once and then ask for input again.


Solution

  • Just use do-while (rather than while):

    import java.util.Scanner;
    
    public class HeloWrld {
        private static Scanner  scan = new Scanner(System.in);
        private static String  command;
    
        public static void answer() {
            System.out.print("\t> ");
            command = scan.nextLine(); // It needs to be able to read the full line to be able to capture spaces
        }
    
        public static void main(String[] args) {
            do {
                System.out.println("Hello!!");
                answer();
            } while (!command.contains("Hello World!"));
            System.out.println("Good bye.");
        }
    }
    

    Output from a sample run of the above code:

    Hello!!
        > fjbejwkb
    Hello!!
        > Hello World!
    Good bye.