0

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!");
                    }
            */
Mazzone
  • 318
  • 1
  • 4
  • 20

2 Answers2

2

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 "=="?

Community
  • 1
  • 1
Ye Win
  • 2,020
  • 14
  • 21
  • 1
    I'm new to this, so that might take a few tries to get used to. Nonetheless, thanks for your help! – Mazzone Jan 24 '15 at 04:04
2

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).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249