-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

Anna
  • 3
  • 1
  • 2
  • 4
    you can call `trim` before calling `equals("")`. BTW, you should do `name == null` otherwise you will end up with a `NullPointerException` – Lothar Jan 09 '18 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?](https://stackoverflow.com/questions/3247067/how-do-i-check-that-a-java-string-is-not-all-whitespaces) – Malte Hartwig Jan 09 '18 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](https://stackoverflow.com/a/19130501/7653073) to see how that works. – Malte Hartwig Jan 09 '18 at 20:02
  • But then again, if the answer is incorrect, how can I write the code so it automatically goes back to "Name: "? – Anna Jan 09 '18 at 20:24

2 Answers2

2

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

if (string.trim().isEmpty())
Alexandre Annic
  • 9,942
  • 5
  • 36
  • 50
1

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

Vladyslav Nikolaiev
  • 1,819
  • 3
  • 20
  • 39
  • 2
    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 – Bohemian Jan 09 '18 at 20:05