Converting output to include discounts when applicable - java

Here's the code I have so far
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.Random;
public class TicketInfo
{
static final double STUDENT_DISCOUNT = .80;
static final double FACULTY_STAFF_DISCOUNT = .20;
/**
*Prints date, time, section, row, seat,
*price, cost, final cost with discount.
*
*#param args Command line arguements (not used).
*/
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
DecimalFormat fmt = new DecimalFormat("$#,##0.00");
DecimalFormat form = new DecimalFormat("###");
String ticketCode = "";
String event = "";
String date = "";
String time = "";
String section = "";
String row = "";
String seat = "";
String price = "";
String type = "";
String cost = "";
int section1, row1, seat1;
double price1, cost1;
Random generator = new Random();
int random;
System.out.print("Enter your ticket code: ");
ticketCode = userInput.nextLine();
System.out.println();
//Trims any extra white spaces.
ticketCode = ticketCode.trim();
if (ticketCode.length() > 27)
{
//Breaks down the ticket code into parts
type = ticketCode.substring(0, 3);
date = ticketCode.substring(14, 16) + "/"
+ ticketCode.substring(16, 18)
+ "/" + ticketCode.substring(18, 22);
time = ticketCode.substring(22, 24)
+ ":"
+ ticketCode.substring(24, 26);
section = ticketCode.substring(4, 5);
row = ticketCode.substring(5, 7);
seat = ticketCode.substring(8, 9);
price = ticketCode.substring(9, 12);
event = ticketCode.substring(26, ticketCode.length());
cost = ticketCode.substring(10, 14);
//Converts Doubles or Integers in a string into its numeric value.
section1 = Integer.parseInt(section);
row1 = Integer.parseInt(row);
seat1 = Integer.parseInt(seat);
price1 = Double.parseDouble(price);
cost1 = Double.parseDouble(cost);
//Calculate cost based on ticket type
random = generator.nextInt(999999) + 1;
// Print results
System.out.println("Event: " + event + " Date: "
+ date + " Time: " + time);
System.out.println("Section: " + form.format(section1) + " Row: "
+ form.format(row1) + " Seat: " + form.format(seat1));
System.out.println("Price: " + fmt.format(price1) + " Ticket Type: "
+ type + " Cost: " + fmt.format(price1));
System.out.println("Raffle Number: " + random);
}
else
{
System.out.println("Invalid Ticket Code.");
System.out.println("Ticket code must have at least 27 characters.");
}
}
}
Output as of now:
Enter your ticket code: STU01280712500091920151430Auburn vs LSU
Event: Auburn vs LSU Date: 09/19/2015 Time: 14:30
Section: 1 Row: 28 Seat: 7
Price: $125.00 Ticket Type: STU Cost: $125.00
Raffle Number: 939894
I need to make the cost output have discount included. For example, STU type = 80% discount, and F/S type = 20% and REG = no discount.
Goal is to make the cost include the 80% discount for STU ticket type which would make the cost 25.00 for student and 100.00 for faculty with a 20% discount. I think my problem is concerned with constants but I'm not sure since I'm a beginner.

You need to do an "if" condition with the type (LSU, STU, REG)
price1 = Double.parseDouble(price);
if(type.equals("STU")){
price1 = price1 * STUDENT_DISCOUNT;
}
else if(type.equals("LSU")){
price1 = price1 * FACULTY_STAFF_DISCOUNT;
}

Related

Adding more classes to a prewritten program

I am being tasked with adding 2 more classes to a prewritten program, one that does all calculations and one that prints the total bill. I understand how to add other classes but im a bit confused since the program already looks like it does the calculations inside of the main class.
Ive tried just adding in the classes but it throws errors because its missing information obviously.
public static void main(String[] args)
{
String squantity, snumber, output, line_output = "";
String [] item = new String [5];
double [] cost = new double [5];
double [] quantity = new double [5];
double [] amount = new double [5];
int number, i;
double grandtotal = 0;
String costout, amountout, grandtotalout;
DecimalFormat df2 = new DecimalFormat("$##,###.00");
for(i=0;i<=4;++i)
{
output = " Acme Grocery Store" + "\n" +
"1-Green Beans $0.35 per pound" + "\n" +
"2-Yellow Beans $0.40 per pound" + "\n" +
"3-Head Lettuce $0.79 per pound" + "\n" +
"4-Leaf Lettuce $1.98 per pound" + "\n" +
"5-Hot House Tomatoes $0.99 per pound" + "\n" +
"6-Hydro Tomatoes $3.98 per pound" + "\n" + "\n" +
"Please make your selection ";
snumber = JOptionPane.showInputDialog(null,
output, "Input Data", JOptionPane.QUESTION_MESSAGE);
number = Integer.parseInt(snumber);
squantity = JOptionPane.showInputDialog(null,
"Enter Quantity", "Input Data", JOptionPane.QUESTION_MESSAGE);
quantity[i] = Double.parseDouble(squantity);
//code for the calculation
if(number == 1)
{
cost[i] = 0.35;
item[i]="Green Beans";
}
else if(number == 2)
{
cost[i] = 0.4;
item[i]="Yellow Beans";
}
else if(number == 3)
{
cost[i] = 0.79;
item[i]="Head Lettuce";
}
else if(number ==4)
{
cost[i] = 1.98;
item[i]="Leaf Lettuce";
}
else if (number==5)
{
cost[i] = 0.99;
item[i]="Hot House Tomatoes";
}
else
{
cost[i] = 3.98;
item[i]="Hydro Tomatoes";
}
amount[i]=cost[i]*quantity[i];
costout=df2.format(cost[i]);
amountout=df2.format(amount[i]);
line_output=line_output+item[i]+" "+costout+" "+amountout+"\n";
grandtotal=grandtotal + amount[i];
}//for loop
grandtotalout=df2.format(grandtotal);
output=line_output+"\n"+ "The total grocery bill = "+grandtotalout;
JOptionPane.showMessageDialog(null, output, " ", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}//main
We are expected to add the classes
class grocery {
}
class printbill{
}
I tried messing with the extends function but I dont think that is correct either
As a starter, your grocery class would look something like this:
final class Grocery
{
Grocery(String InputItem, double InputCost, double InputQuantity)
{
Item = InputItem;
Cost = InputCost;
Quantity = InputQuantity;
}
public final String GetItem()
{
return Item;
}
public final double GetCost()
{
return (double)InputQuantity * Cost;
}
private final String Item;
private final double Cost;
private final int Quantity;
}
The PrintBill class may go like this:
final class PrintBill
{
PrintBill(Grocery [] InputGroceries)
{
Groceries = InputGroceries;
}
public final void Print()
{
double Cost, TotalCost = 0.0;
String Line = "";
String Item;
for (int i = 0; i < Groceries.length; i++)
{
Cost = Groceries[i].GetCost();
Item = Groceries[i].GetItem();
TotalCost += Cost;
// I'll leave it up to you to print this info out.
Line = Item + " " + Cost +" "+ TotalCost +"\n";
}
JOptionPane.showMessageDialog(null, output, " ",
JOptionPane.INFORMATION_MESSAGE);
}
private final Grocery [] Groceries;
}
Your main() would then be:
public static void main(String[] args)
{
String squantity, snumber, output, line_output = "";
Grocery [] Groceries = new Grocery [4];
PrintBill TheBill;
int number;
for (int i = 0; i < Groceries.length; i++)
{
output = " Acme Grocery Store" + "\n" +
"1-Green Beans $0.35 per pound" + "\n" +
"2-Yellow Beans $0.40 per pound" + "\n" +
"3-Head Lettuce $0.79 per pound" + "\n" +
"4-Leaf Lettuce $1.98 per pound" + "\n" +
"5-Hot House Tomatoes $0.99 per pound" + "\n" +
"6-Hydro Tomatoes $3.98 per pound" + "\n" + "\n" +
"Please make your selection ";
snumber = JOptionPane.showInputDialog(null,
output, "Input Data", JOptionPane.QUESTION_MESSAGE);
number = Integer.parseInt(snumber);
squantity = JOptionPane.showInputDialog(null,
"Enter Quantity", "Input Data", JOptionPane.QUESTION_MESSAGE);
quantity = Double.parseDouble(squantity);
if(number == 1)
{
Groceries[i] = new Grocery("Green Beans", 0.35, quantity);
}
else if(number == 2)
{
Groceries[i] = new Grocery("Yellow Beans", 0.4, quantity);
}
// etc...
}
TheBill = new PrintBill(Groceries);
TheBill.Print();
}
More work is required to actually complete this but it should give you a starting point anyway.
Happy Days :-)

JavaFX Loop through array and find a match, otherwise try again

I have a GUI based e-store project. I read in a file and parse through it and saved it into an array.
The file format is like so: 11111, "title", 9.90
11111 is the book id, "title" is title, and 9.90 is the price.
I currently have 3 classes in my project. 1 class for Input/Output, 1 class for the Book store GUI code, and another for pop-up boxes when specific buttons are clicked.
In the GUI code, I check read the file into String[] fileArray and then loop through it until there is a match (with TextField input String bookIds = bookIdinput.getText())
I'm able to successfully get a match and go on with the rest of the code, but when there isn't a match, I get an error: Exception in thread "JavaFX Application Thread" java.lang.NullPointerException at windowDisplay.lambda$start$3(windowDisplay.java:###)
which is this line of code for(int i=0; i<fileArray.length; i++)
If there isn't a match, then it should show a pop-up box saying that bookID isn't found.
Below is some of the GUI code
public class windowDisplay extends Application
{
// Variable declarations
private String[] fileArray = null;
private String holdStr = "";
private Stage mainWindow;
private boolean matchFound = false;
private int count = 1;
private int lineItems = 1;
private double totalAmount = 0.0;
private double subTotal = 0.0;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception
{
// OMITTED CODE
// These TextFields show the output depending on the input TextField's.
itemInfoOutput.setDisable(true);
orderSubtotalOutput.setDisable(true);
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
int qtyItems = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
// Loop through array to find match or no matches
for(int i=0; i<fileArray.length; i++)
{
// If there is a match in book ID
if (fileArray[i].equals(bookIDs))
{
double price = Double.parseDouble(fileArray[i + 2]); // Price is in the i+2 position
double discount = calculateDiscount(qtyItems);
totalAmount = calculatePrice(qtyItems, price);
itemInfoOutput.setText(fileArray[i] + " " + fileArray[i + 1] + " " + "$" + price + " " +
qtyItems + " " + discount + "%" + " " + "$" + df.format(totalAmount));
// Disable processItem Button if there is a match and enable confirmItem Button
processItem.setDisable(true);
confirmItem.setDisable(false);
matchFound = true;
}
}
if(matchFound == false)
System.out.println("No match found!");
});
}
// OMITTED CODE
// This method calculates the discount depending on the quantity of items
public static double calculateDiscount(int inputQty){return null;}
// This methdod calculates the price with the discount
public static double calculatePrice(int inputQty, double price){return null;}
}
This class reads the file and returns an array with the contents of that file (once split by the ", " delimitter).
public class bookStoreIO
{
// This method reads the input file "inventory.txt" and saves it into an array.
public static String[] readFile(String stringIn)
{
try
{
String nextLine;
String[] fIn;
// Read file
BufferedReader br = new BufferedReader(new FileReader("inventory.txt"));
while((nextLine = br.readLine()) != null)
{
fIn = nextLine.split(", "); // Split when ", " is seen
if(stringIn.equalsIgnoreCase(fIn[0]))
{
br.close(); // Close file
return fIn; // Return array
}
}
}
// Just in case file isn't found
catch(IOException e)
{
System.out.println("File not found.");
}
return null;
}
I apologize if this seems messy, I'm still new to JavaFX and Java programming.
If you think more code is needed, please let me know!
EDIT: I improved some variable naming and removed the for loop. I'm still having trouble checking when there isn't a match.
public class windowDisplay extends Application
{
// Variable declarations
private String[] fileArray = null;
private Stage mainWindow;
private boolean matchFound = false;
private int count = 1;
private int lineItems = 1;
private double totalAmount = 0.0;
private double subTotal = 0.0;
private int itemQty = 0;
private int idBook = 0;
private String bookTitle = "";
private double bookPrice = 0.0;
private double discountAmount = 0.0;
private String resultOrder = "";
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception
{
// OMITTED CODE
// These TextFields show the output depending on the input TextField's.
itemInfoOutput.setDisable(true);
orderSubtotalOutput.setDisable(true);
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
itemQty = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
idBook = Integer.parseInt(fileArray[0]);
bookTitle = fileArray[1];
bookPrice = Double.parseDouble(fileArray[2]);
discountAmount = calculateDiscount(itemQty);
totalAmount = calculatePrice(itemQty, bookPrice);
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
itemInfo.setText("Item #" + count + " info:");
processItem.setDisable(true);
confirmItem.setDisable(false);
matchFound = true;
if(matchFound == false)
System.out.println("not found");
});
// OMITTED CODE
// This method calculates the discount depending on the quantity of items
public static double calculateDiscount(int inputQty){return null;}
// This method calculates the price with the discount
public static double calculatePrice(int inputQty, double price){return null;}
}
I'm also having trouble saving
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
into an String or String array to print out a list of all the corresponding matches (along with their book ID, book Title, book Price, quantity, discount , and total price).
An example is shown below:
enter image description here
EDIT 2: The right box is the main GUI. The bottom left box is what shows up when a wrong book is entered (on the 2nd order). The top left is the length of the array.
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
itemQty = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
for(int i=0; i<fileArray.length; i++)
System.out.println(fileArray[i]);
if(fileArray.length >= 3)
{
idBook = Integer.parseInt(fileArray[0]);
bookTitle = fileArray[1];
bookPrice = Double.parseDouble(fileArray[2]);
discountAmount = calculateDiscount(itemQty);
totalAmount = calculatePrice(itemQty, bookPrice);
resultOrder = itemInfoOutput.getText();
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
resultOrder = idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount);
itemInfo.setText("Item #" + count + " info:");
processItem.setDisable(true);
confirmItem.setDisable(false);
}
else
alertBox.confirmDisplay("Book ID " + idBook + " not in file");
});

Running a Java file from Eclipse on Mac

I'm writing a simple Java program for my history final project and am having trouble exporting it out of eclipse so it can be run on my teacher's computer (a Mac).
Here is the code:
package project;
import java.util.Scanner;
public class Denim {
public static void main(String []args) {
Scanner scan = new Scanner(System.in);
System.out.println("What item of denim is in question?");
String str = scan.nextLine();
String str1 = str.toUpperCase();
String jeans = "JEANS";
String jeansp = "JEAN PANTS";
String tux = "CANADIAN TUXEDO";
String tux1 = "CANADIEN TUXEDO";
String tux2 = "CANADIAN TUX";
String tux3 = "CANADIEN TUX";
String jacket = "JACKET";
String jjacket = "JEAN JACKET";
String hat = "HAT";
String dhat = "DENIM BASEBALL HAT";
String bhat = "BASEBALL HAT";
String c = "C";
int jeanFactor = 9982;
double jacketFactor = 10466.25178;
double bottleFactor = 128/16.9;
double hatFactor = 314.1415;
if (str1.equals(jeans) || str1.equals(jeansp)){
System.out.println("How many pairs of jeans?");
int numj = scan.nextInt();
int gallonj = numj*jeanFactor;
System.out.println("Producing " + numj + " pairs of jeans would use: ");
System.out.println(gallonj + " gallons of water");
double bottlesj = gallonj*bottleFactor;
System.out.println(bottlesj + " bottles of water");}
else if ((str1.equals(tux)) || (str1.equals(tux1)) || (str1.equals(tux2)) ||(str.equals(tux3))){
System.out.println("How many tuxedos?");
int numt = scan.nextInt();
int gallontp = numt * jeanFactor;
double gallontj = numt * jacketFactor;
double gallont = gallontp + gallontj;
double bottlest = gallont*bottleFactor;
System.out.println("Producing " + numt +" " + c + str.substring(1,8) + " tuexedos would use: ");
System.out.println(gallont +" gallons of water.");
System.out.println(bottlest + " bottles of water");}
else if (str1.equals(jacket) || str.equals(jjacket)){
System.out.println("How many jackets?");
int numjj = scan.nextInt();
double gallonjj = numjj*jacketFactor;
double bottlesjj = numjj*bottleFactor;
System.out.println("Producing " + numjj + " jackets would use: ");
System.out.println(gallonjj + " gallons of water");
System.out.println(bottlesjj + " bottles of water");}
else if (str1.equals(hat) || str.equals(dhat) || str.equals(bhat)){
System.out.println("How many hats?");
int numh = scan.nextInt();
double gallonh = numh*hatFactor;
double bottlesh = numh*bottleFactor;
System.out.println("Producing " + numh + " jackets would use: ");
System.out.println(gallonh + " gallons of water");
System.out.println(bottlesh + " bottles of water");
}
}
}
I click file-export and export it as a .jar file, but every time I try and open it to run it, a message pops up saying "The Java JAR file could not be launched. Does anyone know how to fix this or what I'm doing wrong? Both my computer and my teacher's are Macbooks.

In this foreach loop, undesired characters are being printed in the terminal

I'm working on a program to calculate heat index, and am supposed to make heavy use of foreach loops. However, when I print to the terminal, it doesn't come out right. I've already spent two days on this, but I still cannot find out why it's still doing this. Thanks for any help/advice!
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class HeatIndex {
public static void main(String[] args) throws IOException {
Scanner keyWestHumidScan = new Scanner(new File("KeyWestHumid.txt"));
Scanner keyWestTempScan = new Scanner(new File("KeyWestTemp.txt"));
int counter1 = 0;
int counter2 = 0;
double[] keyWestHumid = new double[12];
double[] keyWestTemp = new double[12];
String header1 = " Heat index: Key West, Florida ";
String header2 = "\n Months \n ";
String[] months = {" Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec ", "Avg \n"};
String header3 = "*****************************************************************************************";
String temp = "Temp (F) ";
String humid = "Hudimitiy (%) ";
String heatIndexHeader = "HI (F) ";
//read keyWestHumid into array
while (keyWestHumidScan.hasNext()) {
String data1_parse = keyWestHumidScan.next();
double data1 = Double.parseDouble(data1_parse);
keyWestHumid[counter1] = data1;
counter1++;
}
//read keyWestTemp into array
while (keyWestTempScan.hasNext()) {
String data2_parse = keyWestTempScan.next();
double data2 = Double.parseDouble(data2_parse);
keyWestTemp[counter2] = data2;
counter2++;
}
System.out.println(header1);
System.out.print(header2);
for (String headData : months) {
System.out.print(headData);
}
System.out.println(header3);
System.out.print(temp);
for (double data : keyWestTemp) {
System.out.print(keyWestTemp + " ");
}
System.out.println();
System.out.print(humid);
for (double data : keyWestHumid) {
System.out.print(keyWestHumid + " ");
}
System.out.println();
System.out.print(heatIndexHeader);
counter1 = 0;
counter2 = 0;
for (int counter3 = 0; counter3 <= 12; counter3++) {
double heatIndex = (-42.379 + (2.04901523 * keyWestTemp[counter1]) + (10.14333127 * keyWestHumid[counter2]) - (0.22475541 * keyWestTemp[counter1] * keyWestHumid[counter2]) - (0.00683783 * (keyWestTemp[counter1] * keyWestTemp[counter1])));
heatIndex = heatIndex + (-0.05481717 * (keyWestHumid[counter2] * keyWestHumid[counter2]) + (0.00122874 * (keyWestTemp[counter1] * keyWestTemp[counter1] * keyWestHumid[counter2])) + 0.00085282 * keyWestTemp[counter1] * (keyWestHumid[counter2] * keyWestHumid[counter2]) - (0.00000199 * (keyWestTemp[counter1] * keyWestTemp[counter1]) * (keyWestHumid[counter2] * keyWestHumid[counter2])));
counter1++;
counter2++;
counter3++;
System.out.print(heatIndex + " ");
}
}
}
You are printing out the collection of objects, and not the individual objects themselves. For instance: for (double data : keyWestTemp) { System.out.print(keyWestTemp + " ");
}
Should actually be: for (double data : keyWestTemp) {
System.out.print(data + " ");
}
To start, your code is pretty hard to read. Make sure you are following good code style (indent 4 spaces inside a for loop block, for example). Read through this: http://www.oracle.com/technetwork/java/codeconv-138413.html
From glancing through your code, could the porblem be here:
for(double data:keyWestTemp) {
System.out.print(keyWestTemp + " ");
}
and here:
for(double data:keyWestHumid) {
System.out.print(keyWestHumid + " ");
}
I think you want to be using data in the print line, instead of keyWestHumid/Temp. data is the object, keyWestHumid/Temp is your whole array.
You should really be using an IDE such as Eclipse or Netbeans, it will make your life much easier. Right away Eclipse tells you that data isn't used in these loops, which is a problem.
Use System.out.printf to format your text to be displayed on the console.
System.out.printf("%10s%10s", "Number", "String");
System.out.println("");
System.out.printf("%10d", 10);
System.out.printf("%10s", "Hi there");

No errors but part of code that should display type and amount of pizzas ordered is not working

public class PizzaExamfinalOne{
public static void main(String[]args){
double total2 = 0;
String customerName = " ";
String address = " ";
String phoneNum ="0";
int max = 5;
int done = 1;
double totalPizza = 0;
double totalA = 0;
int pizzaChoice =0;
String [] pizzaType = {"Placeholder", "Hawaian" , "Classic Italian" , "Cheese Extreme" , "Veg Delight" , "Pepperoni" , "Tomato Margherita" , "Beef & Onion" , "Super Supreme" , "Meat Lovers" , "Hot 'n Spicy" , "Italiano" , "Italian Veg"};
double [] pizzaPrice = {0, 8.5 , 8.5 , 8.5 , 8.5 , 8.5 , 8.5 , 8.5 , 13.5 , 13.5 , 13.5 , 13.5 , 13.5};
int [] orderDisplay = {0,0,0,0,0,0,0,0,0,0,0,0,0};
boolean pickup = true;
int pickup1 = readInt("If you wish to pickup press 1 or press 0 for delivery");
if (pickup1 ==0){
pickup = false;
}
for (int i = 1; i <pizzaType.length; i++){
System.out.println(i + " " +pizzaType[i] + " $" + pizzaPrice[i]);
}
while (done !=0){
pizzaChoice = readInt ("Choose the type of pizza you wish to order");
double pizzaQuantity = readInt ("How many " + pizzaType[pizzaChoice] + " pizzas do you wish to buy (Maximum is 5)");
totalPizza = totalPizza + pizzaQuantity;
if(totalPizza > max){
System.out.println("You cannot order more than five pizzas");
pizzaChoice = 0;
pizzaQuantity = 0;
}
done= readInt ("Press 0 if you are done or press 1 to make another pizza order");
double total1 = pizzaQuantity*pizzaPrice[pizzaChoice];
total2 = total2 + total1;
}
if(pickup==false){
int deliveryCost = 3;
customerName = readString ("Please enter your full name");
address = readString ("Please enter the Delivery address");
phoneNum = readString ("Please enter the phone number of " + customerName);
totalA = total2 + deliveryCost;
System.out.println("Delivery order for " + customerName);
System.out.println("To " + address + ", Phone number 0" + phoneNum);
}
else{
customerName = readString ("Please enter your full name");
System.out.println("Pickup order for " + customerName);
int deliveryCost = 0;
totalA = total2 + deliveryCost;
}
My problem is here. I need to display the pizzas that the user has ordered along with the amount of pizzas ordered and I'm stuck here. there are no errors in the code it just doesnt display the following
for(int i=1;i<orderDisplay.length;i++){
if(orderDisplay[i]>0){
System.out.println(" " + orderDisplay[i] + " " + pizzaType[i] + " pizzas");
}
}
System.out.println("The total amount of your order is " + formatMoney(totalA));
}
public static int readInt(String prompt){
System.out.println(prompt);
java.util.Scanner keyboard = new java.util.Scanner(System.in);
return keyboard.nextInt();
}
public static String readString (String prompt){
System.out.println (prompt);
java.util.Scanner keyboard= new java.util.Scanner(System.in);
return keyboard.nextLine();
}
public static String formatMoney(double phoneNum){
java.text.NumberFormat fmt = java.text.NumberFormat. getCurrencyInstance();
return(fmt.format(phoneNum));
}
}
You don't add orders to your orderDisplay array.
You should handle it in if(pickup==false){..}
You have set all the array elements of orderDisplay to 0.
int [] orderDisplay = {0,0,0,0,0,0,0,0,0,0,0,0,0};
U never changed the value of orderDispaly elements and checking for value greater than 0 and u have started your loop with value 1. check the below lines.
for(int i=1;i<orderDisplay.length;i++){
if(orderDisplay[i]>0){
System.out.println(" " + orderDisplay[i] + " " + pizzaType[i] + " pizzas");
}
Here is your answer :
public class PizzaExamFinalOne
{
public static void main(String[]args)
{
double total2 = 0;
String customerName = " ";
String address = " ";
String phoneNum ="0";
int max = 5;
int done = 1;
double totalPizza = 0;
double totalA = 0;
int pizzaChoice =0;
String [] pizzaType = {"Placeholder", "Hawaian" , "Classic Italian" , "Cheese Extreme" , "Veg Delight" , "Pepperoni" , "Tomato Margherita" , "Beef & Onion" , "Super Supreme" , "Meat Lovers" , "Hot 'n Spicy" , "Italiano" , "Italian Veg"};
double [] pizzaPrice = {0, 8.5 , 8.5 , 8.5 , 8.5 , 8.5 , 8.5 , 8.5 , 13.5 , 13.5 , 13.5 , 13.5 , 13.5};
int [] orderDisplay = {0,0,0,0,0,0,0,0,0,0,0,0,0};
boolean pickup = true;
int pickup1 = readInt("If you wish to pickup press 1 or press 0 for delivery");
if (pickup1 == 0)
{
pickup = false;
}
while (done != 0)
{
for (int i = 1; i <pizzaType.length; i++)
{
System.out.println(i + " " +pizzaType[i] + " $" + pizzaPrice[i]);
}
pizzaChoice = readInt ("Choose the type of pizza you wish to order");
int pizzaQuantity = readInt ("How many " + pizzaType[pizzaChoice] + " pizzas do you wish to buy (Maximum is 5)");
totalPizza = totalPizza + pizzaQuantity;
if(totalPizza > max)
{
totalPizza = totalPizza - pizzaQuantity;
System.out.println("You cannot order more than five pizzas");
pizzaChoice = 0;
pizzaQuantity = 0;
}
else
{
orderDisplay[pizzaChoice] = pizzaQuantity;
}
done= readInt ("Press 0 if you are done or press 1 to make another pizza order");
double total1 = pizzaQuantity*pizzaPrice[pizzaChoice];
total2 = total2 + total1;
}
if(totalPizza > 0)
{
if(pickup == false)
{
int deliveryCost = 3;
customerName = readString ("Please enter your full name");
address = readString ("Please enter the Delivery address");
phoneNum = readString ("Please enter the phone number of " + customerName);
totalA = total2 + deliveryCost;
System.out.println("Delivery order for " + customerName);
System.out.println("To " + address + ", Phone number 0" + phoneNum);
}
else
{
customerName = readString ("Please enter your full name");
System.out.println("Pickup order for " + customerName);
int deliveryCost = 0;
totalA = total2 + deliveryCost;
}
for(int i=1;i<orderDisplay.length;i++)
{
if(orderDisplay[i]>0)
{
System.out.println(" " + orderDisplay[i] + " " + pizzaType[i] + " pizzas");
}
}
System.out.println("The total amount of your order is " + formatMoney(totalA));
}
else
{
System.out.println("You have not ordered anything.");
}
}
public static int readInt(String prompt)
{
System.out.println(prompt);
java.util.Scanner keyboard = new java.util.Scanner(System.in);
return keyboard.nextInt();
}
public static String readString (String prompt)
{
System.out.println (prompt);
java.util.Scanner keyboard= new java.util.Scanner(System.in);
return keyboard.nextLine();
}
public static String formatMoney(double phoneNum)
{
java.text.NumberFormat fmt = java.text.NumberFormat. getCurrencyInstance();
return(fmt.format(phoneNum));
}
}

Categories