> IN JAVA, Can someone tell me how to get my code to keep a running total of all taxes entered when -1 is entered. CODE SO

IN JAVA, Can someone tell me how to get my code to keep a running total of all taxes entered when -1 is entered. CODE SO

Posted at: 2014-12-18 
Move the totalTax=totalTax+tax BEFORE the the keyboard.nextFloat call if you want the last tax entered to be part of the total.

Move the System.out.println call too if you want the last line to get a running total. That would eliminate the need for an if (income==-1) statement.

One thing, especially for money amounts, is that float is a poor data type. Amounts of around $2,000 have a representation error of about 1/10 cent and it doesn't take too many in a sum to get totals that don't quite balance. Use double (and scanner.nextDouble()) as your main floating point data type, unless you have a specific reason to sacrifice precision for storage.

//Tax rates, brackets, constants

final static double TAX1 = 0.10;

final static double TAX2 = 0.15;

final static double TAX3 = 0.33;

final static double BRACKET1 = 15000.00;

final static double BRACKET2 = 15001.00;

final static double BRACKET3 = 60000.00;



public static void main(String[] args) {

//Keyboard as input

Scanner keyboard = new Scanner (System.in);



//Defining variables

float income;

double tax=0;

double totalTax=0;



//Getting income from user

System.out.println("Please input the income, type -1 to end");

income=keyboard.nextFloat();





while(income!=-1){

if (income<=BRACKET1){

tax=income*TAX1;



System.out.println ("The tax on $" + income + " is $" + tax);

}



if (income==BRACKET2 && income<=BRACKET3){

tax=(BRACKET1*TAX1) + (income-BRACKET1)*TAX2;



System.out.println ("The tax on $" + income + " is $" + tax);

}



if (income>BRACKET3){

tax=(BRACKET1 * TAX1) + (BRACKET3-BRACKET1) * TAX2 + (income-BRACKET3)*TAX3;



System.out.println ("The tax on $" + income + " is $" + tax);

}



System.out.println("Please input the income, type -1 to end");

income=keyboard.nextFloat();



//Displaying total taxes when enter -1

if (income==-1){

totalTax=totalTax + tax;

System.out.printf("The total tax is $%.2f", totalTax);

}

//END OF PROGRAM







}

}

}