Adding up prices from an Array in Java? - java

I have some review questions for an upcoming test in my Java class, the one I am working on at the moment asks us to create a cafe menu with two arrays, one with menu items and the other with prices. We have to print the average of all the prices before asking the user which item(s) from the menu they want and then finally print the total of the items.
My code:
import java.util.Scanner;
public class cafeMenu {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int choice;
double total = 0;
//Array for storing prices
double [] cafePrice = new double[5];
cafePrice[0]= 6.99;
cafePrice[1]= 5.99;
cafePrice[2]= 2.99;
cafePrice[3]= 1.50;
cafePrice[4]= 2.50;
//Menu item array
String [] cafeDrink = new String[5];
cafeDrink[0] = "Macchiato";
cafeDrink[1] = "Latte";
cafeDrink[2] = "Americano";
cafeDrink[3] = "Tea";
cafeDrink[4] = "Cappichino";
//Welcome user and gather their menu selection
System.out.println("Welcome to our cafe! Please enjoy!");
System.out.printf("The average pricing for our drinks is: %.2f \n", + cafeAvg( cafePrice));
System.out.println("Please enter a menu selection:\n"
+ "0. Macchiato -- $6.99\n"
+ "1. Latte -- $5.99\n"
+ "2. Americano -- $2.99\n"
+ "3. Tea -- $1.50\n"
+ "4. Cappichino -- $2.50");
choice = input.nextInt();
//Add up the total
for(int i = 0; i < cafePrice.length; i++ ) {
if(choice == cafePrice[i]) {
total += cafePrice[i];
}
}
System.out.println("Your total is: " + total);
}
//Method for average menu price
public static double cafeAvg(double[] array) {
double sum = 0;
double sum2 = 0;
for(int i = 0; i < array.length; i++) {
sum += array[i];
sum2 = sum /array.length;
}
return sum2;
}
}
I haven't set up a do while loop just yet to continue to ask the user for input because I've sort of gotten stuck with adding the prices together. I'd imagine I've made an error in my for loop, or possibly a logic error?
This is the result I keep getting, regardless of the choice made:
Welcome to our cafe! Please enjoy!
The average pricing for our drinks is: 3.99
Please enter a menu selection:
0. Macchiato -- $6.99
1. Latte -- $5.99
2. Americano -- $2.99
3. Tea -- $1.50
4. Cappichino -- $2.50
4
Your total is: 0.0
Any ideas would be greatly appreciated.

You are doing the following incorrectly,
if(choice == cafePrice[i]) {
total += cafePrice[i];
}
choice is an int while cafeprice[i] is a double ... moreover they represent different things. You actually want to do the following I think,
total += cafePrice[choice];
instead of the whole for loop.
This code works for me,
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int choice;
double total = 0;
//Array for storing prices
double [] cafePrice = new double[5];
cafePrice[0]= 6.99;
cafePrice[1]= 5.99;
cafePrice[2]= 2.99;
cafePrice[3]= 1.50;
cafePrice[4]= 2.50;
//Menu item array
String [] cafeDrink = new String[5];
cafeDrink[0] = "Macchiato";
cafeDrink[1] = "Latte";
cafeDrink[2] = "Americano";
cafeDrink[3] = "Tea";
cafeDrink[4] = "Cappichino";
//Welcome user and gather their menu selection
System.out.println("Welcome to our cafe! Please enjoy!");
System.out.printf("The average pricing for our drinks is: %.2f \n", + cafeAvg( cafePrice));
System.out.println("Please enter a menu selection:\n"
+ "0. Macchiato -- $6.99\n"
+ "1. Latte -- $5.99\n"
+ "2. Americano -- $2.99\n"
+ "3. Tea -- $1.50\n"
+ "4. Cappichino -- $2.50");
choice = input.nextInt();
//Add up the total
total += cafePrice[choice];
System.out.println("Your total is: " + total);
}
//Method for average menu price
public static double cafeAvg(double[] array) {
double sum = 0;
double sum2 = 0;
for(int i = 0; i < array.length; i++) {
sum += array[i];
sum2 = sum /array.length;
}
return sum2;
}

Related

I cant get my nested loop to average student scores correctly after first loop

This is my Java programming class assignment: Write a program, that takes users’ input and the number of students, and test scores. It should then average test scores and display them on the screen. (Wants us to do this using a nested loop).
The issue that I am having is when the program goes into the second loop the sum is still totaling the scores from the previous loop. so it is throwing off any student average calculated after the first one.
'Import java.util.Scanner;'
class Main { public static void main(String[] args) {
int ans, ans1;
double sum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("\n\nFor how many students do you have scores ? ");
ans = sc.nextInt(); //Number of Students
for (int x=1; x<=ans; x++) {
System.out.print("\n\nHow many test scores does student #" + x+" have? ");
ans1 = sc.nextInt(); //Number of scores entered
for (int z=1; z<=ans1; z++) {
double ans2;
System.out.print("\nEnter score "+z+" for student " +x+": ");
ans2 = sc.nextDouble();
sum += ans2 + 0; //Student Scores
}
double avg = sum/ans1;
System.out.printf("\nStudent #"+x+" Average Score: %.1f", avg);
}
}
}
Output:
For how many students do you have scores ? 2
How many test scores does student #1 have? 3
Enter score 1 for student 1: 84
Enter score 2 for student 1: 79
Enter score 3 for student 1: 97
Student #1 Average Score: 86.7
How many test scores does student #2 have? 3
Enter score 1 for student 2: 92
Enter score 2 for student 2: 88
Enter score 3 for student 2: 94
Student #2 Average Score: 178.0 //Average should be 91.3
You should reset the sum variable inside the loop.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int ans, ans1;
double sum = 0;
Scanner key = new Scanner(System.in);
System.out.println("\nHow many students have scores?: ");
ans = key.nextInt();
for(int i = 0; i < ans; i++){
System.out.print("\nHow many test scores does Student "+ (i+1) + " have?: ");
ans1 = key.nextInt();
for(int j = 0; j < ans1; j++){
double ans2;
System.out.print("\nEnter score " + (j + 1) + " for Student " + (i + 1) +": ");
ans2 = key.nextDouble();
sum += ans2;
}
double avg = sum/ans1;
System.out.printf("\nStudent " + (i + 1) + " Average score: %.1f", avg);
sum = 0; //add this line
}
}
}
The "sum" variable should be inside the ans loop as it must be reset for each student. :)

How can I add the values that I got from multiplying two arrays?

So I am creating an invoice program and I got stuck at the part when I have to get the total I got from multiplying two arrays. I am able to multiply them and I get the values but unfortunately more than one value if I enter more than one item. I want to be able to add the values I get to get a total.
To give you an idea, here's my code:
public static void main(String []args){
Scanner input = new Scanner(System.in);
String sentinel = "End";
String description[] = new String[100];
int quantity[] = new int[100];
double price [] = new double[100];
int i = 0;
// do loop to get input from user until user enters sentinel to terminate data entry
do
{
System.out.println("Enter the Product Description or " + sentinel + " to stop");
description[i] = input.next();
// If user input is not the sentinal then get the quantity and price and increase the index
if (!(description[i].equalsIgnoreCase(sentinel))) {
System.out.println("Enter the Quantity");
quantity[i] = input.nextInt();
System.out.println("Enter the Product Price ");
price[i] = input.nextDouble();
}
i++;
} while (!(description[i-1].equalsIgnoreCase(sentinel)));
System.out.println("Item Description: ");
System.out.println("-------------------");
for(int a = 0; a <description.length; a++){
if(description[a]!=null){
System.out.println(description[a]);
}
}
System.out.println("-------------------\n");
System.out.println("Quantity:");
System.out.println("-------------------");
for(int b = 0; b <quantity.length; b++){
if(quantity[b]!=0){
System.out.println(quantity[b]);
}
}
System.out.println("-------------------\n");
System.out.println("Price:");
System.out.println("-------------------");
for(int c = 0; c <price.length; c++){
if(price[c]!=0){
System.out.println("$"+price[c]);
}
}
System.out.println("-------------------");
//THIS IS WHERE I MULTIPLY THE PRICE AND THE QUANTIY TOGETHER TO GET THE TOTAL
for (int j = 0; j < quantity.length; j++)
{
//double total;
double total;
total = quantity[j] * price[j];
if(total != 0){
System.out.println("Total: " + total);
}
}
}
}
In your last for loop, you're only multiplying the quantity and the price of the item and putting it as the value of total instead of adding it to total. Also every time it loops it creates a new total.To make it better, declare total out of the loop and move your if statement out
double total = 0.0;
for (int j = 0; j < quantity.length; j++){
total += quantity[j] * price[j];
}
if(total != 0){
System.out.println("Total: " + total);
}

Brand new to Java, need some help restarting a while loop

I have just started learning Java in the last week or so and I'm creating a program that acts as a sales calculator that calculates commission.
My code is as follows:
import java.util.Scanner;
public class Application {
int itemOne;
int itemTwo;
int itemThree;
int itemFour;
final double baseCommission = 200;
final double itemOnePrice = 239.99;
final double itemTwoPrice = 129.75;
final double itemThreePrice = 99.95;
final double itemFourPrice = 350.89;
final double commissionPercentage = 0.09;
boolean startLoop = false;
public void start(){
while (startLoop = false);
{
//Welcome message
System.out.println("Welcome to Devon's Sales Calculator!");
//Defining new scanner
Scanner user_input = new Scanner(System.in);
//Getting user input for salesperson name along with number of items sold as well as assigning them to a variable
String salesman_name;
System.out.print("Insert salesperson name:\t");
salesman_name = user_input.next();
System.out.print("Enter number of first item sold:\t");
int first_item = user_input.nextInt();
System.out.print("Enter number of second item sold:\t");
int second_item = user_input.nextInt();
System.out.print("Enter number of third item sold:\t");
int third_item = user_input.nextInt();
System.out.print("Enter number of fourth item sold:\t");
int fourth_item = user_input.nextInt();
//Printing out the name of the salesmen, followed by the total price of items sold
System.out.println("Sales Person\t" + salesman_name);
System.out.println("Total price of first item sold\t" + first_item * itemOnePrice);
System.out.println("Total price of second item sold\t" + second_item * itemTwoPrice);
System.out.println("Total price of third item sold\t" + third_item * itemThreePrice);
System.out.println("Total price of fourth item sold\t" + fourth_item * itemFourPrice);
//Calculating total of all items sold
double finalPrice = first_item * itemOnePrice + second_item * itemTwoPrice + third_item * itemThreePrice + fourth_item * itemFourPrice;
//Calculating commission # 0,9%
System.out.println("Total commission earned\t" + finalPrice * commissionPercentage);
//Decision whether or not to restart the while loop
String decision;
System.out.println("Would you like to check another salesperson?");
decision = user_input.next();
if(decision == "yes"){
startLoop = false;
}
else if(decision == "no"){
startLoop = true;
}
}
}
}
Whenever I execute my while loop, it doesn't restart to choose another salesman. I'm probably doing something horribly wrong and my code formatting is probably horrible. Any help would be appreciated.
Get rid of the = false and the semicolon. So not:
while (startLoop = false);
{
System.out.println("foo");
}
which is equivalent to
while (startLoop = false) {
// do nothing
}
{
System.out.println("foo");
}
Instead do,
while (!startLoop) {
// do something here
}

How do I make an exit for my loop?

This is for an assignment in my class. It is to make an automatic ordering system. I'm still new to Java so everything doesn't necessarily click just yet. I think most things work for the most part but the main thing I am having trouble with is making the loop itself and making an exit for it.
import java.util.Scanner;
public class Metal {
public static void main (String[] args) {
double PRICE1 = 5.00;
double PRICE2 = 7.00;
double PRICE3 = 3.50;
double PRICE4 = 0.75;
double TAX = 0.05;
System.out.println ("Metal Down Your Mouth Menu");
System.out.println ();
System.out.println ();
System.out.println ();
System.out.println ("1. Black Sabbath Burgers (Hamburgers With Black Buns) " + PRICE1);
System.out.println ("2. Rack of Lamb of God (Rack of Lamb) " + PRICE2);
System.out.println ("3. Texas Hippie Collar Greens (Collar Greens) " + PRICE3);
System.out.println ("4. Pepsi " + PRICE4);
System.out.println ("Press any other button to stop ordering.");
Scanner userInput = new Scanner(System.in);
int itemnumber = 0;
while (itemnumber < 1 || itemnumber > 4) {
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
}
System.out.print ("How many?");
int amount = userInput.nextInt();
double subtotal = 0;
double total = 0;
double price = 0;
double taxes = 0;
String name = "";
switch (itemnumber){
case 1: name = "Black Sabbath Burgers"; price = PRICE1; break;
case 2: name = "Rack of Lamb of God"; price = PRICE2; break;
case 3: name = "Texas Hippie Collar Greens"; price = PRICE3; break;
case 4: name = "Pepsi"; price = PRICE4; break;
}
subtotal = price * amount;
total = subtotal + total;
System.out.print("Price for items: " + subtotal);
System.out.print("Price Total: " + total);
}
This is my first time posting on this site, but I think I found your problem. There are two large errors, indicated by the arrows:
while (itemnumber >= 1 || <-- itemnumber <= 4) {
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
} <--
1) This should be a '&&' not a '||'. You want it to be within the range. Right now the number it reads has to be greater than or equal to 1 OR less than or equal to 4, which is all integers.
2) You close your loop prematurely. What your code does right now (after the && switch) is it takes numbers 1-4 and keeps repeating the "Enter the item number...." line until you put a number not in the range, then it continues.
The fix: there are a few ways to fix this. My fix would be thus, and the explanation will come after:
import java.util.Scanner;
public class Metal {
public static void main (String[] args) {
double PRICE1 = 5.00;
double PRICE2 = 7.00;
double PRICE3 = 3.50;
double PRICE4 = 0.75;
double TAX = 0.05;
System.out.println ("Metal Down Your Mouth Menu");
System.out.println ();
System.out.println ();
System.out.println ();
System.out.println ("1. Black Sabbath Burgers (Hamburgers With Black Buns) " + PRICE1);
System.out.println ("2. Rack of Lamb of God (Rack of Lamb) " + PRICE2);
System.out.println ("3. Texas Hippie Collar Greens (Collar Greens) " + PRICE3);
System.out.println ("4. Pepsi " + PRICE4);
System.out.println ("Press any other button to stop ordering.");
Scanner userInput = new Scanner(System.in);
int itemnumber = 0;
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
double total = 0;
while (itemnumber >= 1 && itemnumber <= 4) {
System.out.print ("How many?");
int amount = userInput.nextInt();
double subtotal = 0;
double price = 0;
double taxes = 0;
String name = "";
switch (itemnumber)
{
case 1: name = "Black Sabbath Burgers"; price = PRICE1; break;
case 2: name = "Rack of Lamb of God"; price = PRICE2; break;
case 3: name = "Texas Hippie Collar Greens"; price = PRICE3; break;
case 4: name = "Pepsi"; price = PRICE4; break;
}
subtotal = price * amount;
total = subtotal + total;
System.out.print("Price for items: " + subtotal);
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
}
System.out.print("Price Total: " + total);
}
}
Explanation: In essence, you had like 90% of it. I moved the mentioned '}' to the end here:
itemnumber = userInput.nextInt();
} <--
That way, it loops over this code until the user ends.
Additionally, your loop does not need much fixing. It can be used with the && fix. However, you have to put that top line before the loop.
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
And then you put the same line at the end of the loop to reset itemnumber. What your loop does is if itemnumber is between 1 and 4, it executes the following code. Otherwise, it stops. By checking before you enter the loop, you set itemnumber so that way the loop has something to check. And you put the next input at the end of the loop so that way your program finishes totaling its first execution before moving on to the next.
Additionally, you should move the variable 'total' out of the loop as seen above. If you keep looping over it and resetting it to 0, your total will output 0 every time. Best to keep the creation of total out of the loop, and its modification inside the loop.
Small tip, use System.out.println(); instead of System.out.print(); it puts the outputs on its own line. Looks a little nicer.
I think that covers it. If you want more explanation, I'd be more than happy to give it to you. Java is pretty fun once you get used to it. It just takes time. :D

Desired output calculation wrong?

I've written this program but am running into a logical error upon compilation.
My input would be 1, 2, 6, 10 for the selection of products and the coinciding output should be
Total items ordered: 3
Price of items ordered: $747.00
Sales Tax: $48.55
Total amount due: $795.55
Strangely enough it is giving me
Total items ordered: 3
Price of items ordered: $6611.00
Sales Tax: $429.715
Total amount due: $7040.715
Is there an error within my for loop conditions or calculations, or my array that is leading to this hyper-inflated output?
import java.util.Scanner;
public class GrapefruitOrderingArray {
//Declare Constants
public static final int SIZE = 100;
public static final int[] itemPrices = {49,299,329,399,199,1299,1199,999,599};
public static void main(String[] args) {
// Declare Variables
Scanner input = new Scanner (System.in);
String CustomerName;
int[] naNumber = new int [SIZE];
int nProducts = 0;
double nTotal = 0;
double dFinalPrice = 0.0;
int nCount = 0;
//Declare Constants
final int SENTINEL = 10;
final double SALES_TAX = 0.065;
//Prompt user to enter name
System.out.println("Please enter your name: ");
//Enter user name
CustomerName = input.nextLine();
System.out.println("");
//Begin Product Listing Declarations with respect to array above
System.out.println("GRAPEFRUIT PRODUCT:");
System.out.println("1. gPod shuffle $" + itemPrices[0]);
System.out.println("2. gPod Touch $" + itemPrices[1]);
System.out.println("3. gPad Mini $" + itemPrices[2]);
System.out.println("4. gPad 2 $" + itemPrices[3]);
System.out.println("5. gPhone $" + itemPrices[4]);
System.out.println("6. gMac $" + itemPrices[5]);
System.out.println("7. MacNovel Pro $" + itemPrices[6]);
System.out.println("8. MacNovel Air $" + itemPrices[7]);
System.out.println("9. MiniMac $" + itemPrices[8]);
System.out.println("10. Complete my order");
//Keep reading until the input is terminated by sentinel
System.out.println("\nPlease select an item from the menu above: ");
//Read number entered by the user
naNumber[nCount] = input.nextInt();
//Begin while-loop statement
while (naNumber[nCount] != SENTINEL) {
System.out.println("\nPlease select another item from the menu above: ");
nCount++;
//Read number entered by the user
naNumber[nCount] = input.nextInt();
}
System.out.println("Thank you for ordering with Grapefruit Company, " + CustomerName);
//Call final price calculation
dFinalPrice = calculateTotalPrice(naNumber,itemPrices,nTotal);
//Print blank line to screen
System.out.println("");
//Total amount of product ordered
System.out.println("Total items ordered: " + nCount );
//Total price of items ordered
System.out.println("Price of items ordered: $" + dFinalPrice );
//Sales tax associated with the purchase
System.out.println("Sales tax: $" + SALES_TAX * dFinalPrice );
//Total amount due by the customer to Grapefruit Co.
System.out.println("Total amount due: $" + (SALES_TAX * dFinalPrice + dFinalPrice ));
} //End main method
private static double calculateTotalPrice(int[] naNumber, int[] itemPrices) {
double total = 0;
//Calculate entered items
for(int i = 0; i < naNumber.length; i++){
if(naNumber[i] != 0) {
total += itemPrices[naNumber[i] - 1];
}
}
return total;
}
} //end class calculateTotalPriceOfItemsOrdered
You naNumber will contain numbers from 1 to 9. This means that you'll be multiplying the item prices by some large numbers at some points, hence why you're getting large totals.
What I think you want to do is
double itemTotal = itemPrices[naNumber[i] - 1];
nTotal += itemTotal;
Without multiplying itemPrices[i] by naNumber[i]
Also you don't really need to pass nTotal to the method and initialise a double with every loop. You can just declare a field outside the loop:
double total = 0;
Use it inside the loop like this:
total += itemPrices[naNumber[i] - 1];
And return it at the end of the method.
So your method would look something like that:
private static double calculateTotalPrice(int[] naNumber, int[] itemPrices) {
double total = 0;
//Calculate entered items
for(int i = 0; i < naNumber.length; i++){
if(naNumber[i] != 0) {
total += itemPrices[naNumber[i] - 1];
}
}
return total;
}
There are three problems here.
You put the sentinel value, 10, into the array of items the user has chosen.
You use the loop index rather than the number the user chose when calculating price.
You multiply the price of each item by its number. So the user buys 6 of item 6.
In your main method, you need to read the user's input into another variable, and only insert it into the array if it is not the sentinel value.
In your calculateTotalPrice method, you should calculate the price of an individual line item like this:
double itemTotal = itemPrices[naNumber[i] - 1];

Categories

Resources