Search code examples
javastringnullbufferedreader

Java: Checking for changes in a String with BufferedReader


If trying to get user input into a string, using the code:

String X = input("\nDon't just press Enter: ");

and if they did't enter anything, to ask them until they do.

I've tried to check if it's null with while(x==null) but it doesn't work. Any ideas on what I am doing wrong/need to do differently?

input() is:

  static String input (String prompt)
    {
        String iput = null;
        System.out.print(prompt);
        try
        {
            BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
            iput = is.readLine();

        }

        catch (IOException e)
        {
            System.out.println("IO Exception: " + e);
        }
        return iput; 
        //return iput.toLowerCase(); //Enable for lowercase
    }

Solution

  • In order to ask a user for an input in Java, I would recommend using the Scanner (java.util.Scanner).

    Scanner input = new Scanner(System.in);
    

    You can then use

    String userInput = input.nextLine();
    

    to retrieve the user's input. Finally, for comparing strings you should use the string.equals() method:

    public String getUserInput(){
        Scanner input = new Scanner(System.in);
        String userInput = input.nextLine();
        if (!userInput.equals("")){
            //call next method
        } else {
            getUserInput();
        }
    }
    

    What this "getUserInput" method does is to take the user's input and check that it's not blank. If it isn't blank (the first pat of the "if"), then it will continue on to the next method. However, if it is blank (""), then it will simply call the "getUserInput()" method all over again. There are many ways to do this, but this is probably just one of the simplest ones.