Desired output calculation wrong? - java

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];

Related

Adding up prices from an Array in 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;
}

How do I get inputs from a user and find the highest, lowest, and average of them?

I am in the process of writing code that asks the user for their name, how many jobs they have, and the income of those jobs. Then the code finds the highest and lowest paying incomes, and the average of the jobs they entered.
Im having issues with the highest and lowest paying portion, along with finding the average, while still maintaining what the user entered in order to recite it later.
Ex:
Inputs: 10000 30000 50000
"Hello Audrey. You have had 3 jobs. The highest paying job paid $50000. The lowest paying job paid $10000. The average pay for the jobs entered is $30000
**** heres the code I have edited, but it is not running properly. I believe it has to do with int and double. Im not sure which code should be double and which ones should be int.****
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class JobIncome {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner (System.in);
System.out.println("What is your first name? ");
String firstName = input.nextLine();
Scanner scan = new Scanner (System.in);
System.out.println("How many jobs have you had? ");
int jobNum = scan.nextInt();
//Declarations
int total = 0;
int average = 0;
//for loop asks for the incomes of the user's previous
//jobs and stores them into an array
int arrayOfIncomes[] = new int[jobNum];
for(int i = 1; i <= arrayOfIncomes.length; i++){
System.out.println("Enter the income of job #" + i + " : ");
arrayOfIncomes[i] = scan.nextInt();
total = total + arrayOfIncomes[i];
}
average = total/jobNum;
//Start of the code that will find the min and max
int min = arrayOfIncomes[0];
int max = arrayOfIncomes[0];
for (int i = 1; i < arrayOfIncomes.length; i++) {
if (arrayOfIncomes[i] > max) {
max = arrayOfIncomes[i];
}
}
for (int i = 1; i < arrayOfIncomes.length; i++) {
if (arrayOfIncomes[i] < min) {
min = arrayOfIncomes[i];
}
}
//Print statement that gives the user all their information
System.out.println("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");
//Prompt asking the user if they would like to print their info into a text file
System.out.println("Would you like to output your information into a text file, yes or no? ");
String yesNo = input.nextLine();
if(yesNo.equals("yes")){
System.out.println("");
} else {
System.out.println("Goodbye.");
}
//Output code
Scanner console = new Scanner(System.in);
System.out.print("Your output file: ");
String outputFileName = console.next();
PrintWriter out = new PrintWriter(outputFileName);
//This code prints the information into the output text file
out.print("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");
out.close();
}
Fix the code by instantiating an array, jobIncomes with the length equivalent to the number of jobs. You could keep a running average, but you would lose precision when rounding. You will also need to instantiate three integer variables: total, max and min, each at zero.
For every iteration of the loop, you should add the following code:
jobIncomes[i-1]=s.nextInt();
if (jobIncomes[i-1]<min)
{ min=jobIncomes[i-1];}
if (jobIncomes[i-1]>max
{max=jobIncomes[i-1];}
total+=jobIncomes[i-1];
When you print the average, you can cast the formula average = total/jobNum. You might also want to change the array values to read from 0 to jobNum-1, if you want to index simply by i in the if statements.
Create an int variable sum. Add the sum as you get input from the user then divide the sum with the variable jobNum while casting at least one variable to double.
Example:
double ave = (double) sum / jobNum;

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

Writing for loops/while loops?

I'm in a programming class in high-school, and I was given an assignment to make a basic subtotal and top calculator, but I work at a restaurant, so it seemed a little pointless to make a calculator that only let you read in one food. So I tried to make it able to take in multiple food items and add them to one price variable. Sorry if some of this code may seem inefficient or redundant. It's only high-school of course.
The issue is, when I run it, it gets up to the asking if there was another food item the user would like to add, and when I type in "Yes" or "No", the program does nothing. Keeps running, but goes no further. Any explanations?
import java.text.NumberFormat;
import java.util.Scanner;
public class Price {
/**
* #param args
*/
public static void main(String[] args) {
final double taxRate = .0887; //8.87% Tax Rate
double tipRate;
int quantity1;
Scanner kb = new Scanner(System.in);
double subtotal, tax, tip, totalCost1, unitPrice1 = 0;
String done;
System.out.println ("How many of the first item did you get?: ");
quantity1 = kb.nextInt();
for (int i = 0; i < quantity1; i++)
{
System.out.println ("What was the price of that single item "+(i+1) + ": ");
unitPrice1 = kb.nextDouble();
System.out.println ("Was there another food item you'd like to add?: ");
done=kb.next();
while (done.equalsIgnoreCase("Yes"));
}
System.out.println ("What percent would you like to tip? (Formatted like 0.10 for 10%, 0.20 for 20%, etc.): ");
tipRate = kb.nextDouble();
subtotal= quantity1 * unitPrice1;
tax = subtotal * taxRate;
totalCost1 = subtotal + tax;
tip = totalCost1 * tipRate;
totalCost1 = totalCost1 + tip;
//Formatting
NumberFormat money = NumberFormat.getCurrencyInstance();
NumberFormat tipMoney = NumberFormat.getCurrencyInstance();
NumberFormat taxPercent = NumberFormat.getPercentInstance();
NumberFormat tipPercent = NumberFormat.getPercentInstance();
System.out.println ("Your total before tax is: " + money.format(subtotal));
System.out.println ("The tax is " + money.format(tax) + " at " + tipPercent.format(taxRate));
System.out.println ("The tip at " + tipPercent.format(tipRate) + " is " + tipMoney.format(tip));
}
}
You have an infinite loop here:
while (done.equalsIgnoreCase("Yes"));
Once you enter Yes, it will keep sitting there and doing nothing because the value of done is Yes and never changes.
Also your loop structure is a bit odd. Your outer for loop runs as many times as the quantity of the first item. But shouldn't you only be multiplying that number to the cost? Because you are either running the loop for as long as the number of items the user entered (by asking them up front) or you don't ask them the total number of items and simply ask them to enter Yes if they want to add more items; you can't really do both.
Your loop should probably look something like this:
String input = "Yes";
while(input.equalsIgnoreCase("Yes")) {
System.out.println ("How many of the first item did you get? ");
quantity1 = kb.nextInt();
System.out.println ("What was the price of that single item? ");
unitPrice1 = kb.nextDouble();
//total += unitPrice1 * quantity1 - you don't have this in your code, but this is where you would be calculating the running total
System.out.println("Was there another food item you'd like to add? ");
input = kb.next();
}
you need to exit for loop when user enters yes, so you can use label here like below:
outerloop:
for (int i = 0; i < quantity1; i++)
{
System.out.println ("What was the price of that single item "+(i+1) + ": ");
unitPrice1 = kb.nextDouble();
System.out.println ("Was there another food item you'd like to add?: ");
done=kb.next();
while (done.equalsIgnoreCase("Yes")){
break outerloop;
}
}
Your current code does not do anything inside the while loop if you don't enter yes. And if you enter yes it will be stuck in infinite loop because of your while loop. This is not the efficeint way of looping, but this code will have least change in your current code.
You're while loop is doing nothing, you had given it a condition, but it has no instruction.
Try something like this..(sorry for my rusty java)
'public static void main(String[] args) {
//variable declaration
bool running = true
final double taxRate = .0887; //8.87% Tax Rate
double tipRate;
int quantity1;
Scanner kb = new Scanner(System.in);
double subtotal, tax, tip, totalCost1, unitPrice1 = 0;
String done;
while(running = true){
System.out.println ("How many of the first item did you get?: ");
quantity1 = kb.nextInt();
for (int i = 0; i < quantity1; i++)
{
System.out.println ("What was the price of that single item "+(i+1) + ": ");
unitPrice1 = kb.nextDouble();
System.out.println ("Was there another food item you'd like to add?: ");
done=kb.next();
if(done.equalsIgnoreCase("No")){
running = false
//Allows you to break out of the while loop if the user does not want to add anything else
//DO NOT USE BREAK STATMENTS, IT IS A POOR PROGRAMMING PRACTICE.
};//end if
}//end for
}//end while
System.out.println ("What percent would you like to tip? (Formatted like 0.10 for 10%, 0.20 for 20%, etc.): ");
tipRate = kb.nextDouble();
//You should comment whats going on here
subtotal= quantity1 * unitPrice1;
tax = subtotal * taxRate;
totalCost1 = subtotal + tax;
tip = totalCost1 * tipRate;
totalCost1 = totalCost1 + tip;
//Formatting
NumberFormat money = NumberFormat.getCurrencyInstance();
NumberFormat tipMoney = NumberFormat.getCurrencyInstance();
NumberFormat taxPercent = NumberFormat.getPercentInstance();
NumberFormat tipPercent = NumberFormat.getPercentInstance();
//Output
System.out.println ("Your total before tax is: " + money.format(subtotal));
System.out.println ("The tax is " + money.format(tax) + " at " + tipPercent.format(taxRate));
System.out.println ("The tip at " + tipPercent.format(tipRate) + " is " + tipMoney.format(tip));
}//end main

I am having an issue when trying to call the "calculateTotalPrice" method back into the main method to compute the final pricing

I've written the following program and am having an issue when trying to call the "calculateTotalPrice" method back into the main method to compute the final pricing. I'm not sure if it is an error with my method or my call. Main works as desired without the call to the "calculateTotalPrice" method. Can anyone give any suggestions as to how I should rearrange the secondary method or call statement? Thanks
public class GrapefruitOrderingArray {
//Declare Constants
public static final int SIZE = 100;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// Declare Variables
Scanner input = new Scanner (System.in); //Input new scanner system
String CustomerName; //Declare customer's name as a string
int nNumber = 0; //Declare integer variable for nNumber
int nProducts = 0; //Declare integer variable for nproducts
int nTotal; //Declare integer variable for ntotal
double[] nFinalPrice = new double [SIZE];
int [] itemPrices = {49,299,329,399,199,1299,1199,999,599}; //Declare integer variable array
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();
//Print Blank Line
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 10
System.out.println("\nPlease select an item from the menu above: ");
//Begin while-loop statement
while (nNumber != SENTINEL) {
//Read number entered by the user
nNumber = input.nextInt();
if (nNumber == SENTINEL) {
System.out.println("Thank you for ordering with Grapefruit Company, " + CustomerName);
break;
}
//Call final price calculation
nFinalPrice = calculateTotalPrice(nNumber);
//If desired the user may select another or multiple products now
System.out.println("\nPlease select another item from the menu above: ");
}
//Print blank line to screen
System.out.println("");
//Total amount of product ordered
System.out.println("Total items ordered: " + nProducts );
//Total price of items ordered
System.out.println("Price of items ordered: $" + nTotal );
//Sales tax associated with the purchase
System.out.println("Sales tax: $" + SALES_TAX * nTotal );
//Total amount due by the customer to Grapefruit Co.
System.out.println("Total amount due: $" + (SALES_TAX * nTotal + nTotal));
}
} //End main method
/**
* This method calculates the total price of the products ordered
* #param itemPrice Individualized product prices
* #param nProduct Total price of items paid for
* #return nTotals Returns the number of the product associated with it's initialized price
*/
private static double[] calculateTotalPrice(int nNumber) {
//Calculate entered items
nTotal = nTotal + itemPrices [nNumber-1];
//Increment the total number of products entered
nProducts++;
return nNumber;
} //end method calculateTotalPriceOfItemsOrdered
} //end class calculateTotalPriceOfItemsOrdered
There are several problems here:
int nTotal =0; Happens after int nTotal is taken in as a parameter.
SIZE isn't declared anywhere.
More of a side note, but your comments are overly excessive.
This program returns the total price of the items selected by a customer. Hope it will help you.
import java.util.*;
public class CalTotalPrice {
static int totalPrice=0;
static int [] itemPrices = {49,299,329,399,199,1299,1199,999,599};
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
//declaring variables
String CustomerName;
int itemNumber = 0;
int noOfProducts = 0;
final int SENTINEL = 10;
final double SALES_TAX = 0.065;
//Getting customer name
System.out.println("Please enter your 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");
System.out.print("\nPlease select an item from the menu above: ");
while (itemNumber != SENTINEL) {
itemNumber = input.nextInt();
if (itemNumber <= SENTINEL) {
System.out.println("Thank you for ordering with Grapefruit Company, " + CustomerName);
break;
}
noOfProducts++; //increse number of products ordered
totalPrice= calculateTotalPrice(itemNumber);
System.out.print("\nPlease select another item from the menu above: ");
}
System.out.println("");
System.out.println("Total items ordered: " + noOfProducts);
System.out.println("Price of items ordered: $" +totalPrice);
System.out.println("Sales tax: $" + SALES_TAX *totalPrice);
System.out.println("Total amount due: $" + (SALES_TAX *totalPrice+totalPrice));
}
public static int calculateTotalPrice(int itemNumber) {
totalPrice=totalPrice+ itemPrices[itemNumber-1];
return totalPrice;
}
}

Categories

Resources