Here's my code:
public static void addContact() {
Scanner sc = new Scanner(System.in);
//ask the user if they want a personal or business contact
System.out.println("Please 1 if you want to add a personal contact or press 2 for business");
int select = sc.nextInt();
if (select == 1) {
System.out.println("Please enter the user first name");
String firstName = sc.next();
System.out.println("Please enter the user last name");
String lastName = sc.next();
System.out.println("Please enter the user address");
String address = sc.next();
System.out.println("Please enter the user phoneNumber");
String phoneNumber = sc.next();
System.out.println("Please enter the user email");
String email = sc.next();
//ask for confirmation
System.out.println("The following information you enter was : " firstName " " lastName " " address ""
" " phoneNumber " " email " is this information is correct, then please press Y");
String confirm = sc.next().toUpperCase(Locale.ROOT);
do{
if (confirm.equals("Y")) {
contacts.add(new Contact(firstName, lastName, address, phoneNumber, email));
} else {
System.out.println("That was an invalid entry, please press Y to save data");
}
}while(confirm.equals("Y"));
Here's the results:
Please choose from the following selection
press 1 add a contact
press 2 to a view contact
press 3 to exit your contact list
1
Please 1 if you want to add a personal contact or press 2 for business1
1
Please enter the user first name
m
Please enter the user last name
m
Please enter the user address
mm
Please enter the user phoneNumber
n
Please enter the user email
nb
The following information you enter was : m m mm n nb is this information is correct, then please press Y
n
That was an invalid entry, please press Y to save data
Please choose from the following selection
press 1 add a contact
press 2 to a view contact
press 3 to exit your contact list
If the user presses anything then "Y". I want my code to say invalid entry, and then proceed to ask if the information is correct again. However, when the user presses anything else but y, it'll say invalid entry and go back to the menu. How do I fix this problem?
CodePudding user response:
If you want to ask user input again - move your sc.next().toUpperCase(Locale.ROOT);
into your do while block.
Also, add !
to your while condition. Because while loop is working while condition is falsy. So if you want to ask for user input until it equals Y
- then statement should be:
while(!confirm.equals("Y"))