Task is to create a basic calculator using double value and sentinel. I cannot figure out how to get the array to avoid counting the sentinel. To me, it looks like I've put in safeguards such as only looping if the value is >=0, but it still counts, lists, and even adds the sentinel number to the final result. I've tried changing the while statement to !=-1 with no change in the results. I'm a complete Java newbie (obviously), and have tried many options, but can't find the right one.
package arraypractice;
import java.util.ArrayList;
import java.util.Scanner;
public class CashRegister
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
{
final int SENTINEL=-1;
double priceFromUser=0;
double total=0;
double average=0;
double count=0;
boolean done=false;
String trash="";
String lists="";
ArrayList<Double> list = new ArrayList<>();
Scanner in = new Scanner(System.in);
//Prompt user to enter a price, or -1 when finished entering prices.
while (!done)
{
while (priceFromUser >= 0)
{
System.out.println("Please enter item price, or enter -1 to quit.");
if(in.hasNextDouble())//if the input is a double
{
priceFromUser=in.nextDouble(); //read value from user
list.add(priceFromUser); //add valid price to the list
}
else
{
trash=in.nextLine(); //throw away the input
System.out.println("You did not enter a price.");
}
//add valid input to list
//total the prices added by user, and keep track of how many were added
{
total += priceFromUser;
count++;
}
}
//print the array list of entries, the total cost, and the average cost.
list.forEach(System.out::println);
System.out.println("The total price of the items is $" + total +". The average cost per item is: $" + (total/count));
done=true;
}
Output is:
run-single:
Please enter item price, or enter -1 to quit.
25
Please enter item price, or enter -1 to quit.
25
Please enter item price, or enter -1 to quit.
25
Please enter item price, or enter -1 to quit.
25
Please enter item price, or enter -1 to quit.
-1
25.0
25.0
25.0
25.0
-1.0
The total price of the items is $99.0. The average cost per item is: $19.8