0

I just started Java and wanted to tinker with the syntax. Whenever I input "F" into gender and age being greater than or equal to 20 I should be prompted to input if the user is married or not, for some reason the scanner is skipping over it. Everything else works fine.

Output I'm getting:

Whats is your gender (M or F): F
First name: Kim
Last name: Kardashian
Age: 32

Are you married, Kim (Y or N)? 
Then I shall call you Ms. Kardashian.

Code:

import java.util.Scanner;

public class GenderGame 
{

    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);

        int age = 0;
        String Gender = null, fName = null, lName = null, M = null, type = null;

        System.out.print("Whats is your gender (M or F): ");
        Gender = sc.nextLine();
        Gender = Gender.toUpperCase();

        System.out.print("First name: ");
        fName = sc.nextLine();

        System.out.print("Last name: ");
        lName = sc.nextLine();

        System.out.print("Age: ");
        age = sc.nextInt();

        if(Gender.equals("F") && age >= 20)
        {
            System.out.print("\nAre you married, " + fName + " (Y or N)? ");
            M = sc.nextLine();
            M = M.toUpperCase();

            if(M.equals("Y"))
            {
                type = "Mrs. ";
                type = type.concat(lName);
            }
            else
            {
                type = "Ms. ";
                type = type.concat(lName);
            }
        }
        else if(Gender.equals("F") && age < 20)
        {
            type = fName.concat(" " + lName);
        }
        else if(Gender.equals("M") && age >= 20)
        {
            type = "Mr. ";
            type = type.concat(lName);
        }
        else if(Gender.equals("M") && age < 20)
        {
            type = fName.concat(" " + lName);
        }
        else
        {
            System.out.println("There was incorrect input. EXITING PROGRAM");
            System.exit(1);
        }

        System.out.println("\nThen I shall call you " +type+ ".");

    }

}
Derrick Rose
  • 585
  • 7
  • 19

1 Answers1

1

The nextInt() method of Scanner leaves the new line character out, that is, it does not consume it. This newline character is is consumed by your nextLine() method, which is why you do not see it wait for your input.

To avoid this, call sc.nextLine() after age = sc.nextInt();, then leave the rest of code unchanged.

        ...
        System.out.print("Age: ");
        age = sc.nextInt();
        sc.nextLine(); //added

        if(Gender.equals("F") && age >= 20)
        {
            System.out.print("\nAre you married, " + fName + " (Y or N)? ");
            M = sc.nextLine();
            M = M.toUpperCase();

            if(M.equals("Y"))
            {
                type = "Mrs. ";
                type = type.concat(lName);
            }
         ...
iMan
  • 436
  • 1
  • 7
  • 18