Stefan Jankovic
Stefan Jankovic

Reputation: 95

Make user enter String again after invalid input

The program throws out an error when the user enters invalid data but continues to work, how do I force the user to enter data until he enters the correct one? I tried with System.exit(0) but that stop program.

Also tried with while but dont know how to create message to say "Hey invalid input, try again!"

public void setName(String name) {
        if (name.matches("[a-zA-Z]+")) {
            this.name = name;
        } else {
            System.out.println("Only letters for name!");
            System.exit(0);
        }
    }

 public void setName(String name) {
        while (name.matches("[a-zA-Z]+")) {
            this.name = name;
        } else { //how to make message here?
            System.out.println("Only letters for name!");
            System.exit(0);
        }
    }

I saw some previous questions about this but cant find nothing excatly similar to my problem, because I have this regex.

I also have this to add new user:

  System.out.println("Add first name for passenger: ");
    passengers.setName(scanner.nextLine());

That is in my method registerNewPassenger and so on for lastName, email, at the end of method I have this

 ArrayList<Passengers> passengersList = new ArrayList<>();
    passengersList.add(passengers);
    System.out.println(passengersList);

And in my main I just call it.

Upvotes: 0

Views: 360

Answers (2)

Ashish Mishra
Ashish Mishra

Reputation: 724

Keep asking for the name inside the while loop until it matches the regex.

    public void setName() {
    Scanner sc = new Scanner(System.in);
    String name = sc.nextLine();
    while (!name.matches("[a-zA-Z]+")) {
        //Name not matched
        System.out.println("Please Enter a valid name");
        name = sc.nextLine();
    }
    this.name = name;
}

Upvotes: 0

DevilsHnd - 退した
DevilsHnd - 退した

Reputation: 9202

It could be something like this:

private Scanner scanner = new Scanner(System.in);
private String name;

public void setName() {
    String aName = "";
    while (aName.isEmpty()) {
        System.out.print("Enter Name: --> ");
        aName = scanner.nextLine(); 
        if (!aName.matches("[a-zA-Z]+")
            System.err.println("Invalid Entry (" + name + ")! Only letters for name!");
            aName = "";
        }
    }
    this.name = aName;
}

Upvotes: 1

Related Questions