0
public class LabWork {
private String yourStatus;
private int yourIncome;
private double tax;

public int calculateTax () {
    if (yourStatus = "Married" && yourIncome <= 2000) {
        tax = yourIncome/10;
    }
    else if (yourStatus = "Married" && yourIncome > 2000) {
    tax = 3*yourIncome/20;
    }

    else if (yourStatus = "Single" && yourIncome <=2000) {
    tax = 17*yourIncome/100;
    }
    else
    tax = 22*yourIncome/100;
    }

public double getTax () {
    return tax;
}

}

this is my first code and I have a tester class to use this like:

import java.util.Scanner;

public class UseLab3Work {

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("What is your status? ");
    String yourStatus = keyboard.next();
    System.out.println("What is your incomew? ");
    int yourIncome = keyboard.nextInt();

}

}

However, in the first program, I'm getting an error like "String cannot be converted to boolean" at line 7,10 and 14. Then how should I use if with String? For example I have input in tester and when I write there Married, the program should calculate tax related to my String input.

Arsenic
  • 109
  • 6
  • `if (yourStatus = "Married" && yourIncome <= 2000)` ==> `if (yourStatus .equalsIgnoreCase("Married") && yourIncome <= 2000)` ? – TheLostMind Mar 08 '16 at 09:07
  • You're assigning new values to `yourStatus`. Assignment returns the type of the value assigned, which here is a `String`. You could use `yourStatus == "Married"`, etc., but using `.equals()` or `.equalsIgnoreCase()` is much more robust. – Erick G. Hagstrom Mar 08 '16 at 10:28

1 Answers1

4

I first would have thought to mark this a duplicate, since you are comparing your Objects wrong, but it's a step further.

 if (yourStatus = "Married" )

Here, you don't compare the values of the String, you actually just assign it.

 if (yourStatus == "Married")

This would be better, but will produce false results. After all, the == operator is used for referential comparison, while you want to compare values.

if (yourStatus.equals("Married")) (or if (yourStatus.equalsIgnoreCase("Married")) )

would be better, since this is the correct way to compare the values of Strings. An even better way would be:

if ( "Married".equals(yourStatus))

In the other order, if yourStatus is null, it will throw a NullPointerException, which you avoid by calling equals (or equalsIgnoreCase) on the String literal.

Stultuske
  • 9,296
  • 1
  • 25
  • 37