int iItem double dSubtotal double dSalesTax double dTotal do
int iItem;
double dSubtotal;
double dSalesTax;
double dTotal;
double dCost;
// Instantiations:
Scanner cin = new Scanner(System.in);
DecimalFormat dfCurrency= new DecimalFormat(\"$#.00\");
dSubtotal=0;
iItem=1;
dSalesTax =1;
System.out.print(\"Enter item \"+iItem+ \" cost:\");
dCost=cin.nextDouble();
while(iItem!=-1)
{
dCost=cin.nextDouble();
if(iItem!=-1)
{
dSubtotal= dSubtotal+dCost;
iItem++;
}
}
if(iItem>0)
dSalesTax=dSubtotal*0.06;
dTotal =dSubtotal+dSalesTax;
// PROCESSING AND CALCULATIONS
System.out.println(\"Subtotal: \"+dfCurrency.format(dSubtotal));
System.out.println(\"Sales tax: \" +dfCurrency.format(dSalesTax));
System.out.println(\"Total: \" +dfCurrency.format(dTotal));
}
Please help
Recode the previous problem so it can handle any number of items. Base your code on a sentinel-controlled while loop that will terminate the data entry phase when a negative cost is input by the user. Example input dialog follows. Yellow highlight is example end-user input:
One or more item costs entered by the user:
Enter item 1 cost: 14.25
Enter item 2 cost: 50.75
Enter item 3 cost: 10.00
Enter item 4 cost: -1
Items: 3
Subtotal: $75.00
Sales Tax: $4.50
Total: $79.50
A negative cost (sentinel) is entered as the very first item by the user:
No items to process
Solution
Hi,
I have modified the code and highlighted the code changes below.
NumberOfItems.java
import java.text.DecimalFormat;
import java.util.Scanner;
public class NumberOfItems {
public static void main(String[] args) {
int iItem;
double dSubtotal;
double dSalesTax;
double dTotal;
double dCost=0;
// Instantiations:
Scanner cin = new Scanner(System.in);
DecimalFormat dfCurrency= new DecimalFormat(\"$#.00\");
dSubtotal=0;
iItem=1;
dSalesTax =1;
while(dCost!=-1)
{
System.out.print(\"Enter item \"+iItem+ \" cost:\");
dCost=cin.nextDouble();
if(dCost!=-1)
{
dSubtotal= dSubtotal+dCost;
iItem++;
}
}
if(iItem>0)
dSalesTax=dSubtotal*0.06;
dTotal =dSubtotal+dSalesTax;
// PROCESSING AND CALCULATIONS
if(dSubtotal != 0){
System.out.println(\"Subtotal: \"+dfCurrency.format(dSubtotal));
System.out.println(\"Sales tax: \" +dfCurrency.format(dSalesTax));
System.out.println(\"Total: \" +dfCurrency.format(dTotal));
}
else{
System.out.println(\"No items to process\");
}
}
}
Output:
Enter item 1 cost:14.25
Enter item 2 cost:50.75
Enter item 3 cost:10.00
Enter item 4 cost:-1
Subtotal: $75.00
Sales tax: $4.50
Total: $79.50
Enter item 1 cost:-1
No items to process


