I’m coding in java and I’m curious as to why the System.out.println function is being ran twice in my if statement.
If I input "married" and "10000" in the scanner, I get the following, where everything is correct except the duplicated "Because your income is less than 15,000 and you’re married, your rate is 10%":
What is your marital status? Married or Unmarried?married
Marital status is documented as: married
Please Enter your income:
10000
Income is documented as: 10000.0
Because your income is less than 15,000 and you're married, your rate is 10%
Because your income is less than 15,000 and you're married, your rate is 10%
The amount is taxes that you owe is: 1000.0
Here is my code for both classes:
public class TaxCalculator {
public double calculateTax (String maritalStatus, double taxableIncome)
{
if (maritalStatus.equals("married"))
{
if (taxableIncome < 15000)
{
System.out.println("Because your income is less than 15,000 and you're married, your rate is 10%");
return taxableIncome * 0.1;
}
else
{
System.out.println("Because your income is more than 15,000 and you're married, your rate is 20%");
return taxableIncome * 0.2;
}
}
return taxableIncome * 0.3;
}
}
import java.util.Scanner;
public class TaxCalculatorTester extends TaxCalculator {
public static void main(String[] args) {
TaxCalculator sample = new TaxCalculator();
Scanner askScanner = new Scanner (System.in);
System.out.print ("What is your marital status? Married or Unmarried?");
String input = askScanner.next();
String maritalStatus = input;
System.out.println("Marital status is documented as: " + maritalStatus);
System.out.println("Please Enter your income: ");
double income = askScanner.nextDouble();
System.out.println("Income is documented as: " + income);
//double taxDue;
//int status;
if (input.equals("married"))
{
sample.calculateTax(maritalStatus, income);
System.out.println("The amount is taxes that you owe is: " + sample.calculateTax(maritalStatus, income));
}
else
{
sample.calculateTax(maritalStatus, income);
System.out.println("Because you're unmarried, your rate is 30%");
System.out.println("The resulting amount in taxes you owe is: " + sample.calculateTax(maritalStatus, income));
}
}
}
I would ideally like for any response in the "married" field to have the program return "Because you’re married / unmarried, your rate is __" but any time I put it within the if statement it duplicates it for some reason. Since there’s only one option for being unmarried, I was able to move the System.out.println code into the tester, but I couldn’t do the same with the married option.
>Solution :
You call the calculateTax function in lines 23 and 24 of main which since the println function is in the function, it prints twice. I would recommend either putting the println statements in if (input.equals("married")) in the tax calculator, or putting the println statements in if (taxableIncome < 15000) in main. You should only have to call the function once.