-3

So I have a question with my code. A part of my code includes a question for a persons details, and to make sure they answer it correctly. The person cannot answer it blank with whitespace or enter etc. If they answer it incorrectly they're supposed to be sent back to the question again and re-enter their details.

This is how far I've come:

   System.out.println("Name: ");
       String name = scan.nextLine();

   if(name.equals(null) || name.equals("")) {
        System.out.println("Name can't be empty, please enter again.");

   System.out.println("Age: ");
       int age = scan.nextInt();

   if(age.equals(null) || age.equals("")) {
        System.out.println("Age can't be empty, please enter again.");

The thing now is that I'm not quite sure how to handle this if the person answers with whitespace. The code doesn't handle whitespace. Also, how can I make the program automatically go back to ex. "Name:" if it's answered incorrectly?

/Anna

4
  • 4
    you can call trim before calling equals(""). BTW, you should do name == null otherwise you will end up with a NullPointerException Commented Jan 9, 2018 at 19:55
  • 2
    Copy your question title into Google, and this shows up... How do I check that a Java String is not all whitespaces? Commented Jan 9, 2018 at 19:59
  • 1
    Aside from that, you have to change your logic: If the name or the age are empty, you just continue. But instead, you need to scan for them again. You can do this with a while loop. Look at this answer to see how that works. Commented Jan 9, 2018 at 20:02
  • But then again, if the answer is incorrect, how can I write the code so it automatically goes back to "Name: "? Commented Jan 9, 2018 at 20:24

2 Answers 2

2

Use trim(). It will removes whitespaces at the start and the end of the string.

if (string.trim().isEmpty())
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, tried this but still allows me to enter a name with only whitespace...
@Anna look at my comment on your question.
I tried if (name.equals(null) || name.trim().equals("")) {...}. It works when i entered just spaces.
Using isEmpty() makes it somewhat more declarative than using length(): !string.trim().isEmpty()
You're right, i edit my answer.
1

name.matches("\\s*") will return true is name is empty or spaces only, where name is inputed String

1 Comment

FYI you don't need ^ or $ with java's matches(); they are implied because matches() must match the whole input. You also don't need [ or ]. just name.matches("\\s*") is enough

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.