1

How can I get the program to ask for input using the scanner after the if statement?

import java.util.Scanner;

public class App1 {

    public static void main(String[] Args) {

        Scanner keyboard = new Scanner(System.in);

        String gender;
        String fName;
        String lName;
        int age;
        String female = "F";
        String male = "M";
        String a = "";
        String gettingMarried = "y";
        String notGettingMarried = "n";

        System.out.println("What is your gender (M or F)");
        gender = keyboard.nextLine();
        System.out.println("What is your first name?");
        fName = keyboard.nextLine();
        System.out.println("What is your last name?");
        lName = keyboard.nextLine();
        System.out.println("Age:");
        age = keyboard.nextInt();
        System.out.println();

        if (gender.equals(female) && age >= 20) {
            System.out.println("Are you married " + fName + " (y or n?)");
            a = keyboard.nextLine();

        } else if (gender.equals(male) && age >= 20) {
            System.out.println("Are you married" + fName + "(y or n?)");
            a = keyboard.nextLine();
        }

    }
}
08Dc91wk
  • 4,254
  • 8
  • 34
  • 67

1 Answers1

1

It is because you use a nextInt() that only takes the int value and not the full line. When you try again to read with keyboard.nextLine() what you are catching it's the rest of the sentence of the line in which you put the int.

Change the System.out.println(); before your if statement to keyboard.nextLine();

Edit: If you want a more extended explanation about why you have to put keyboard.nextLine(); after your keyboard.nextInt() you can consult my answer in another question with the same problem: Why isn't the scanner input working?

I expect it will be helpful for you!

Community
  • 1
  • 1
Francisco Romero
  • 12,787
  • 22
  • 92
  • 167
  • But the age is a the age which is a int. I get an error when I change it. – Jerry Woods Aug 25 '15 at 01:27
  • Oh no, you don't have to change it. You have to let, as you have, `age = keyboard.nextInt();`. You just have to change the line `System.out.println();` to `keyboard.nextLine()` without storing the value. – Francisco Romero Aug 25 '15 at 01:30
  • Thanks worked well, I'm just trying to figure out what "keyboard.nextLine();" does. – Jerry Woods Aug 25 '15 at 01:36
  • @JerryWoods Look my other answer (in the link of the question that I put above). If it doesn't clearify your doubts just ask to me ;) – Francisco Romero Aug 25 '15 at 01:37