patrickB patrickB - 3 months ago 9
Java Question

Java 'if' and 'if else' statements not printing out

I am new to Java and have recently started coding within the last week. I have tried to build some basic things and did the following:

import java.util.Scanner;

public class App {
public static void main(String[] args){
// creating scanner object
Scanner userSex = new Scanner(System.in);
System.out.println("Enter your sex (male or female): ");
String sex = userSex.nextLine();
System.out.println("Thank you, you entered " + sex );

// new scanner
Scanner userAge = new Scanner (System.in);
System.out.println("Are you a child or adult: ");
String age = userAge.nextLine();
System.out.println("You are a " + sex + " " + age);

if (userAge.equals("child")) {
System.out.println("children");
} else if (userAge.equals("adult")) {
System.out.println("adults");
}
}
}


Unfortunately however, only the top of the code runs. The below code doesn't run and doesn't print anything out even when I enter "child" or "adult".

if (userAge.equals("child")) {
System.out.println("children");
} else if (userAge.equals("adult")) {
System.out.println("adults");
}

Answer

The following works:

import java.util.Scanner;

public class App {
public static void main(String[] args){
    //creating scanner object
    Scanner in = new Scanner(System.in);
    System.out.println("Enter your sex (male or female): ");
    String sex = in.next(); 
    System.out.println("Thank you, you entered " + sex );

    //new scanner
    System.out.println("Are you a child or adult: ");
    String age = in.next();
    System.out.println("You are a " + sex + " " + age);

    if(age.equals("child")) {
        System.out.println("children");
    }
    else if(age.equals("adult")) {
        System.out.println("adults");
    }

    }
    }

Rather than creating two separate scanners you just use one and call the next()method. I also change the condition from if(userAge... to if(age...