-3

Alrighty, so I have a program that is supposed to take the first name of the customer, and regardless if the letters in the name are capitalized or lower case, if they are Mike or Diane, it sets the discount to being true and then later on applies the discount. By default discount = false.

Heres getting the name and setting discount to true:

if (firstName == "Mike" || firstName == "Diane")
  {
     discount = true;
  }

And here's later on when I'm trying to apply the discount and lower the cost:

if (discount == true)
  {
     System.out.println("You are eligible for a $2.00 discount!");
     cost = cost - (2.00);
  }

However the problem is that when I use Mike or Diane, whether capitalizing or not, it simply does not apply the discount to the price. It compiles and runs, it just doesn't apply the discount.

WillBro
  • 147
  • 4
  • 16
  • 3
    Use `String`'s `equals` method to compare string values, not the `==` operator. – rgettman Feb 03 '14 at 18:47
  • 1
    1) take a look at [how-do-i-compare-strings-in-java](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). 2) don't use `if (discount==true)`. Just write it as `if(discount)`. This way you will never make mistakes like `if (discount = true)`. – Pshemo Feb 03 '14 at 18:47

4 Answers4

3

Use .equals(...) to compare String values:

"Mike".equals(firstName)

== compares the references of Java Objects. It's perfectly fine to use == to compare primitive data types values (ex. boolean, int, double, etc.).

If you want to ignore the case of the characters, then use .equalsIgnoreCase(...):

"Mike".equalsIgnoreCase(firstName)

Check out the String API, it has a lot of useful methods.

2

You should not use == (reference equality) for determining String equality, luckily there is an String#equalsIgnoreCase(String) method.

boolean discount = ("Mike".equalsIgnoreCase(firstName) || 
    "Diane".equalsIgnoreCase(firstName));
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

== compares the reference of the strings. You can use equals:

Solution:

if(firstName.equalsIgnoreCase("Mike") || firstName.equalsIgnoreCase("Diane"))
{
    discount = true;
}

Tip:

Nevertheless, it is better to write "Mike".equalsIgnoreCase(firstName) instead of firstName.equalsIgnoreCase("Mike"), because you are sure that Mike is not null. firstName.equalsIgnoreCase("Mike") can throw a NullPointerException if firstName is null.

Happy
  • 1,815
  • 2
  • 18
  • 33
1

you can use equalIgnoreCase Method

"Mike".equalsIgnoreCase(firstName)

like

if(firstName.equalsIgnoreCase("Mike") || firstName.equalsIgnoreCase("Diane"))
    {
        discount = true;
    }
Girish
  • 1,717
  • 1
  • 18
  • 30