I am using the scanner in java and am trying to get the program to continue only if an integer is detected for the choice by the user but the code I wrote is not giving that functionality. here is my code :
import java.util.Scanner;
/**
*
* @author Ansel
*/
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
AddressBook ad1 = new AddressBook();
String firstName="";
String lastName="";
String key="";
String street="";
String city="";
String county="";
String postalCode="";
String mNumber="";
int choice=0;
do{
System.out.println("********************************************************************************");
System.out.println("Welcome to the Address book. Please pick from the options below.\n");
System.out.println("1.Add user \n2.Remove user \n3.Edit user \n4.List Contact \n5.Sort contacts \n6.Exit");
System.out.print("Please enter a choice: ");
int reloop = 0;
do {
try {
scan.nextLine();
choice = scan.nextInt();
reloop ++;
} catch (Exception e) {
System.out.println ("Please enter a number!");
}} while(reloop == 0);
if(choice==1){
//Add user
System.out.print("Please enter firstname: ");
firstName=scan.next();
System.out.print("Please enter lastname: ");
lastName=scan.next();
scan.nextLine();
System.out.print("Please enter street:");
street=scan.nextLine();
System.out.print("Please enter city: ");
city=scan.next();
System.out.print("Please enter county: ");
county=scan.next();
System.out.print("Please enter postal code: ");
postalCode=scan.next();
System.out.print("Please enter Mobile number: ");
mNumber=scan.next();
Address address = new Address(street,city,county,postalCode,mNumber);
key = lastName + " ".concat(firstName);
Person person = new Person(firstName,lastName,address);
ad1.addContact(key,person);
System.out.println("key: " + key);
}
else if(choice==2){
//Remove user
System.out.print("Please enter name of user to remove: ");
key=scan.nextLine();
System.out.println("name:" + key);
ad1.removeContact(key);
}
else if(choice==3){
//Edit user
}
else if(choice==4){
//List contact
System.out.println("Enter name of contact you wish to lookup: ");
key=scan.nextLine();
ad1.listContact(key);
}
else if(choice==5){
//Sort contacts
}
else{
System.out.println("Invalid choice entered, please try again");
}
}while(choice!=6);
}
}
the main piece of code that is not functioning correctly is:
int reloop = 0;
do {
try {
scan.nextLine();
choice = scan.nextInt();
reloop ++;
} catch (Exception e) {
System.out.println ("Please enter a number!");
}} while(reloop == 0);
this code when ran asks to enter a number. if you enter a letter, for example, it will show a blank line until you enter another letter and then it will say please enter a number. I don't see why it does not say please enter a number as soon as a letter or anything other than an int is present