1

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

PaPaB1nG0
  • 395
  • 1
  • 3
  • 16
  • Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – itwasntme Sep 17 '19 at 19:06
  • 1
    In addition to the issue you mentioned, it also does not continue correctly when an integer is entered. – arcadeblast77 Sep 17 '19 at 19:20
  • it does after the second attempt – PaPaB1nG0 Sep 17 '19 at 19:25

1 Answers1

3

Just use Scanner.nextLine and Integer.parseInt and save yourself the confusion.

Scanner scan = new Scanner(System.in);
int choice = 0;
System.out.print("Please enter a choice: ");
int reloop = 0;
do {
  try {
    String input = scan.nextLine(); // Scan the next line from System.in
    choice = Integer.parseInt(input); // Try to parse it as an int
    reloop++;
  } catch (Exception e) {
    System.out.println("Please enter a number!");
  }
} while (reloop == 0);

You could also use nextLine after every nextInt to terminate the line, but I prefer parsing the int separately, as above. It's clearer and more verbose.

arcadeblast77
  • 550
  • 2
  • 12
  • it works fine thank you, how is this different from what I was doing to make it work though? – PaPaB1nG0 Sep 17 '19 at 19:30
  • Your original solution was scanning an entire line from input, doing nothing with it, and then scanning a second line up until it found the first integer. This fix simply scans an entire line from input and then parses it as an integer. – arcadeblast77 Sep 17 '19 at 19:42
  • If you are still confused, it is probably because `nextInt` does not do what you think it does. Check out the docs. https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html – arcadeblast77 Sep 17 '19 at 19:42
  • If this answer solved your problem, feel free to mark it as the accepted answer by clicking the checkmark to the left. :) – arcadeblast77 Sep 17 '19 at 19:45
  • 1
    it did and I will, thank you for your help and explanation – PaPaB1nG0 Sep 17 '19 at 19:48