简体   繁体   中英

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
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM