-1

I'm writing a interactive application in Java and one of my local variables isn't adding itself into the class variable which is screwing up my final output.

Here is the class variable public static double deduction;

Here is what I'm trying to store into it

System.out.println("Do you want medical insurance?");
String choice = kb.nextLine();       
if (choice == "yes")
{
    medIns =  32.50;
}
else
{
    medIns = 0;
}
System.out.println("Do you want dental insurance?");
choice = kb.nextLine();
if (choice == "yes")
{
    dentIns = 20.00;
}
else
{
    dentIns = 0;
}
System.out.println("Do you want long-term disability insurance?");
choice = kb.nextLine();
if (choice == "yes")
{
    lifeIns = 10.00;
}
else
{
    lifeIns = 0;
}
deduction = medIns + dentIns + lifeIns;
return deduction;`

Here is what it's finally going into totalpay = gross + (gross * retire) - deduction;

When I put in all the other input it's not storing the local deduction into the class deduction so it can be processed into my totalpay calculation.

Johannes H.
  • 5,875
  • 1
  • 20
  • 40
Kar900
  • 47
  • 1
  • 1
  • 6

1 Answers1

3

Your if/else statements are always false!

deduction = medIns + dentIns + lifeIns; is always deduction = 0 + 0 + 0; no matter what the inputs are given your mis-use of the == operator.

== vs .equals() vs .equalsIgnoreCase()

choice == "yes" is not how you compare Strings in Java, in your case this will never be true.

== compares identity ( is the left hand side the exact same object instance as the right hand side ), .equals() and .equalsIgnoreCase() is how you compare contents of String objects in Java.

Idiomatic Solution

In your case the correct approach is "yes".equalsIgnoreCase(choice.trim()) putting the literal first avoids having to check for null.

a more comprehensive solution would to match on a regular expression

choice.matches("(?i)^y.*") which would match anything that starts with a y and has zero or more characters regardless of case, given that choice isn't null.

Community
  • 1
  • 1
  • 1
    that doesn't answer the question though... – Johannes H. Feb 23 '14 at 19:30
  • 1
    yes it does, the code isn't ever going to add anything but `0` in both those `if/else` blocks. –  Feb 23 '14 at 19:30
  • YOu should add that explanation then. The way your answer reads now, makes it sound like an unrelated comment. I really only realized that you are right now, that I read your comment. – Johannes H. Feb 23 '14 at 19:32
  • Ok Jarrod I replaced choice == "yes" with "yes".equalsIgnoreCase(choice.trim()) and it's still coming up 0?? – Kar900 Feb 23 '14 at 19:54
  • there isn't enough code provided to help you anymore ... we need an [SSCCE](http://www.sscce.org/). –  Feb 24 '14 at 15:47