Correct reading from console in the same line with request

27 Views Asked by At

I'm trying to write request, which user can see in console and in the same line he can give response, but I have some issues with that.

import java.util.Scanner;

public class Main {
    final static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        run();
    }

    public static void run() {
        System.out.println("GREETINGS");
        handleAccountExistence();
    }

    public static void handleAccountExistence() {
        String response;
        do {
            System.out.print("Do you have an account? (y/n): ");
            response = scanner.nextLine();
        } while (!isValidResponse(response));

        if (response.equalsIgnoreCase("y")) {
            System.out.println("enter username");
        } else {
            System.out.println("register need");
        }
    }

    public static boolean isValidResponse(String input) {
        if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("n")) return true;
        else {
            System.err.println("INVALID_INPUT" + "'y' or 'n'.");
            return false;
        }
    }
}

When I'm trying to give incorrect response, I get the next:

GREETINGS
Do you have an account? (y/n): 45
Do you have an account? (y/n): INVALID_INPUT'y' or 'n'.
45
INVALID_INPUT'y' or 'n'.
Do you have an account? (y/n): 54
Do you have an account? (y/n): INVALID_INPUT'y' or 'n'.
54
INVALID_INPUT'y' or 'n'.

Instead of this:

GREETINGS
Do you have an account? (y/n): 45 
INVALID_INPUT'y' or 'n'.
Do you have an account? (y/n): 45
INVALID_INPUT'y' or 'n'.
Do you have an account? (y/n):

I triesd to use System.out.flush(), .trim(), System.out.println(), but it doesn't help in my case.

0

There are 0 best solutions below