2

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
    }
3
  • I seriously have no idea what you're trying to do. Do you mean if(x == null)? Commented Nov 14, 2013 at 3:34
  • I want to check if they didn't enter anything to the string. Question re-worded, thanks. Commented Nov 14, 2013 at 3:36
  • What is the length of iput if they don't enter anything? Commented Nov 14, 2013 at 3:43

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Glad to help! If this solved your problem, please make sure to mark it so future readers will know =)

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.