Mazzone
Mazzone

Reputation: 308

Using result of a scan.nextLine with an if-else statement -- Java

I'm trying to make a BAC (blood alcohol content) calculator that takes inputs from the user and lets them know if they qualify to win... a grand DUI prize! I'm trying to use the Scanner to determine if the person is a male or female and then use an if-then statement down the line based on what the user input...but I don't really know how. It should be a very simple fix, but here's what I have and kinda what I want to do with the if-then statement commented out.

import java.util.*;

public class Proj2_Mazzone
{
    public static void main (String[] args)
    {

        Scanner scan = new Scanner(System.in);

        String gender;
        int D, W, H, age;

...

System.out.print("Enter M if you're a male, or F if you're a female: ");
            gender = scan.nextLine();

            /*if(gender = M)
                {
                    System.out.println("You're a man!");
                }
                else if(gender = F)
                    {
                        System.out.println("You're a woman!");
                    }
            */

Upvotes: 0

Views: 4887

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201507

When comparing String you use .equals() or .equalsIgnoreCase(). Like,

gender = scan.nextLine();
if (gender.equalsIgnoreCase("m")) {
    System.out.println("You're a man!");
} else if (gender.equalsIgnoreCase("f")) {
    System.out.println("You're a woman!");
}

But, you could also compare the first character with something like

if (Character.toUpperCase(gender.charAt(0)) == 'M') {
    System.out.println("You're a man!");
} else if (Character.toUpperCase(gender.charAt(0)) == 'F') {
    System.out.println("You're a woman!");
}

note, that's == (not = which is for assignment).

Upvotes: 2

Ye Win
Ye Win

Reputation: 2098

Use like this:

if(gender.equals("M"))
                {
                    System.out.println("You're a man!");
                }
                else if(gender.equals("F"))
                    {
                        System.out.println("You're a woman!");
                    }

Note: = is assign operator not conditional operator.

You can see how equal condition is work in java at below link.
http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/
What's the difference between ".equals" and "=="?

Upvotes: 2

Related Questions