I'm writing a program that is supposed to display the output based off of some numbers that are typed in. I'm ending up with an output and it is completely blank, and none of the calculations are being performed
/**
*
* #NMATA003PA1.java
* #author Nicholas Mata
* #version 1.00 2015/09/25
*
* Program Purpose: This program controls whether a customer can calculate the cost of his/her stock purchases.
*
*/
import java.util.Scanner; //Scanner is imported to capture user input
import java.util.Calendar;//Calendare is imported to reflect the current date when necessary
public class MataN003PA1
{
public static void main(String[] args)//Customer will be able to calculate costs of multiple trades
{
String customerName = "", date = "";//Customer name and date are declared as Strings
int shares = 0, noOfStocks = 0;//shares and noOfShares are declared as integers, they are set to zero
double sharePrice = 0, stockCost = 0, commission = 0, totalCost = 0, onlineFee = 0, totalStockCost = 0, totalCommissions = 0, totalOnlineFees = 0;
/**
* sharePrice, stockCost, commission, totalCost, onlineFee, totalStockCost, totalCommissions, totalOnline Fees are declared
* as double, they are also set to zero
*/
char onlineTrade = ' ', brokerAssisted = ' ', another = ' '; // onlineTrade and brokerAssisted are declared as char variables, set to blank
Calendar dateTime = Calendar.getInstance(); //dateTime is declared
Scanner input = new Scanner(System.in);
System.out.printf("%nYEE-TRADE, INC. - The Wild West of Electronic Trading"
+"%n%nWelcome to Yee-Trade's stock purchase calculator.%n");
System.out.printf("%n%nWhat is your name? ");
customerName = input.nextLine();
System.out.printf("%nDo you want to calculate your stock purchases? Enter 'Y' or 'N' to exit: ");
another = input.nextLine().charAt(0);
while (Character.toUpperCase(another) == 'Y')
{
noOfStocks = noOfStocks + 1;
System.out.printf("%nHow many shares did you purchase? ");
shares = input.nextInt();
System.out.printf("%nWhat is the price per share? ");
sharePrice = input.nextDouble();
input.nextLine();
stockCost = shares * sharePrice;
totalStockCost = totalStockCost + stockCost;
totalCost = totalCost + stockCost;
System.out.printf("%nIs this an online trade? Enter 'Y' or 'N': ");
onlineTrade = input.nextLine().charAt(0);
if (Character.toUpperCase(onlineTrade) == 'Y')
{
onlineFee = 5.95;
totalOnlineFees = totalOnlineFees + onlineFee;
totalCost = totalCost + onlineFee;
}//END if_1
else
{
System.out.printf("%nIs this a broker assisted trade? Enter 'Y' or 'N': ");
brokerAssisted = input.nextLine().charAt(0);
if (Character.toUpperCase(brokerAssisted) == 'Y')
{
commission = stockCost * .02;
totalCommissions = totalCommissions + commission;
totalCost = totalCost + commission;
}//END if_2
else
{
System.out.printf("%nINVALID TRADE TYPE! %n");
noOfStocks = noOfStocks - 1;
totalStockCost = totalStockCost - stockCost;
totalCost = totalCost - stockCost;
}//end else_2
}//end else_1
System.out.printf("%nEnter 'Y' to calculate the cost of another stock purchase or 'N' to exit: ");
another = input.nextLine().charAt(0);
}//END WHILE LOOP
if (noOfStocks > 0);
{
System.out.printf("%nYEE-TRADE, INC."
+"%nTOTAL COST OF STOCK PURCHASES"
+"%nFOR %s", customerName);
System.out.printf("%nAS OF ");
System.out.printf("%1$TB %1$Td, %1$TY%n", dateTime);
System.out.printf("%nTotal Stock Cost: $", totalStockCost);
System.out.printf("%nTotal Online Fees: $", totalOnlineFees);
System.out.printf("%nTotal Commissions: $", totalCommissions);
System.out.printf("%n%nTOTAL COST: $", totalCost);
}//END if_3
System.out.printf("%nThank you for using Yee-Trade's stock purchase calculator! ");
noOfStocks = 0;
System.exit(0);}//END MAIN
}//END CLASS
You should not always try to format the output if it is not necessary.
Here's your problem :
System.out.printf("%nAS OF ");
System.out.printf("%1$TB %1$Td, %1$TY%n", dateTime);
System.out.printf("%nTotal Stock Cost: $" + totalStockCost);
System.out.printf("%nTotal Online Fees: $", totalOnlineFees);
System.out.printf("%nTotal Commissions: $", totalCommissions);
System.out.printf("%n%nTOTAL COST: $", totalCost);
You'll have to replace most of these with the following
System.out.printf("%nAS OF ");
System.out.printf("%1$TB %1$Td, %1$TY%n", dateTime);
System.out.println("Total Stock Cost: $" + totalStockCost);
System.out.println("Total Online Fees: $" + totalOnlineFees);
System.out.println("Total Commissions: $" + totalCommissions);
System.out.println("TOTAL COST: $" + totalCost);
Here is the output I get :
YEE-TRADE, INC. - The Wild West of Electronic Trading
Welcome to Yee-Trade's stock purchase calculator.
What is your name? Yassin
Do you want to calculate your stock purchases? Enter 'Y' or 'N' to exit: Y
How many shares did you purchase? 50
What is the price per share? 50
Is this an online trade? Enter 'Y' or 'N': Y
Enter 'Y' to calculate the cost of another stock purchase or 'N' to exit: N
YEE-TRADE, INC.
TOTAL COST OF STOCK PURCHASES
FOR Yassin
AS OF OCTOBRE 04, 2015
Total Stock Cost: $2500.0
Total Online Fees: $5.95
Total Commissions: $0.0
TOTAL COST: $2505.95
Thank you for suing Yee-Trade's stock purchase calculator!
Related
None of the other posts seemed to fit accordingly.
I'm really struggling with producing this program without errors. I've come up with this below, however, if you run the program it is not adequately looping and if you choose the same candy twice the math isn't adding to the previous selection.
For the second part, I need to recode to adjust so that the customer may change the current selections if they'd like. So, I need the first part running perfectly.
import java.util.Scanner; //Program uses Scanner
import java.util.Calendar; //Program uses calendar
public class ClairAndreaG005PA2
{//Begin class ClairAndreaG005PA2
public static void main(String[] args)
{
/**Begin method. The customer is asked whether to proceed with a candy purchase.
* As long as the candy choice is in the proper range, prompt for the quantity,
* calculate the item total and subtotal; otherwise, print an error message. If it’s
* the first item in the purchase, ass it to the sales, a receipt with a $ sign for the
* item total. If not format the item without a $ sign for the item total
* and add it to the sales receipt. Start the process again when the customer wants
* to add another candy purchase. When the customer is done, the sales tax and the
* total calculated, the sales receipt is finalized and printed.
*/
int quantity = 0,
formatFirstItem = 1,
choice = 0;
final double TAX_RATE = .0825; //tax rate declared
double price = 0,
itemTotal = 0,
subtotal = 0,
taxAmount = 0,
total = 0;
char proceed = ' '; //proceed variable for loop
String candy = new String();
Calendar dateTime = Calendar.getInstance(); //situational date and time
Scanner input = new Scanner(System.in);
String salesReceipt = String.format("%n%nFAIRYTALE SWEETS%n"
+ "North Star Mall%n"
+ "San Antonio, TX%n"
+ "Date: %n", dateTime
+ "Time: %n", dateTime);
//Initiating variables and calculations
System.out.printf("%nDo you want to proceed with your candy purhase? \'Y\' or \'N\': ");
proceed = input.nextLine().charAt(0);
//End Prompt 1
while(Character.toUpperCase(proceed) == 'Y')
{
System.out.printf("%nFAIRYTALE SWEETS"
+ "%n%n1. Arabian Nights Chocolate Coins - 1 lb. Bag %5s%,7.2f"
+"%n2. Beauty and the Beast Lollipops - 1 lb. Bag %,12.2f"
+"%n3. Mad Hatter Jelly Beans - 1 lb. Bag %,20.2f"
+"%n4. Pinocchio's Candy Cones - Each %,23.2f"
+"%n5. Sleeping Beauty Caramel Apples - Each %,17.2f"
+"%n%nEnter your choice: ", "$", 2.25, 2.50, 1.75, 0.75, 1.25);
choice = input.nextInt();
//Prompt 2 Candy Menu
if(choice > 0)
{if(choice < 6)
{if(choice == 1)
{candy = "Arabian Nights Chocolate Coins";
price = 2.25;
}
else
{if(choice == 2)
{ candy = "Beauty and the Beast Lollipops";
price = 2.50;
}
else
{if(choice == 3)
{candy = "Mad Hatter Jelly Beans";
price = 1.75;
}
else
{if(choice == 4 )
{candy = "Pinocchio's Candy Cones";
price = 0.75;
}
else
{candy = "Sleeping Beauty Caramel Apples";
price = 0.75;
}
}
}
}
System.out.printf("%nQuantity for %s: ", candy);
quantity = input.nextInt();
//quantity of selections
}
else
{ System.out.println("Invalid candy choice! Try again.");
}
//Choices and selections
itemTotal = quantity * price; //calculation 1
subtotal += itemTotal; //calculation 2
System.out.printf("%nWould you like to make another candy purchase? \'Y\' or \'N\': ");
proceed = input.next().charAt(0);
if(formatFirstItem == 1 )
{
salesReceipt += String.format("%n%s"
+ "%n %d # $%.2f ex. %-24s $%,10.2f%n", candy,
quantity, price, " ", itemTotal);
formatFirstItem = 0;
}
else
{
salesReceipt += String.format("%s"
+ "%n %d # $%.2f ea. %-25s %,10.2f%n", candy,
quantity, price, " ", itemTotal);
}
//End if FormatFIrst Item is 1 or else formatFirstItem NOT 1
}
}//End while loop selection
taxAmount = TAX_RATE * subtotal;// calculation 3
total = taxAmount + subtotal; // calculation 4
salesReceipt += String.format("%n%36s %-6s $%,10.2f"
+ "%n%36s %-7s %,10.2f"
+ "%n%n%36s %-6s $%,10.2f%n", "SUBTOTAL: ", " ",
subtotal, "TAX # 8.250%: ", " ", taxAmount,
"TOTAL: ", " ", total);
System.out.printf("%s", salesReceipt);
}
}
Let me know!
Part of the requirement is to replicate the bar graph in https://imgur.com/a/Gx2XOql
I tried this to see if I could rectangle in the dialogue window (obviously it didn't work):
rectMode(CENTER);
// Alberta
if ( prov_id.equals("AB") || prov_id.equals("ab"))
{
if (gross_income>=0&&gross_income<=40000)
{
tax_rate=0.25;
JOptionPane.showMessageDialog(frame,"Province: "+ prov_id + "\nGross Income: "+ gross_income + "\nTax Rate: "+ tax_rate+ "\nTax Amount: "+ tax_amount+"\nNet Income: "+ net_income + rect(10,10,10,10));
}
The rest of my code:
import javax.swing.JOptionPane;
//Input Variables
String prov_id = ""; //province_id will contain the user input for the province (E.g. 'AB').
float gross_income = 0; //gorss_income contains the user input for gross income (E.g. 30000).
//Output Variables:
//You will store the result of your analysis and calculations in these variables
float tax_rate = 0; //Variable tax_rate will hold the tax_rate percentage. You will assign a value for tax_rate based on the Taxable Income (Table 1) table given in the studio project document.
//The value of tax ranges between 0 to 1 (E.g. for Alberta, income of equal or less than $40000 tax = 0.25)
float net_income = 0; //Net income is calculated based on tax_rate. It is the take-home income after taxes are deducted.
//i.e. net_income = gross_income * (1 - tax_rate);
float tax_amount = 0; //tax amount is the amount of taxes paid based on gross income depending on the province.
//i.e. tax_amount = gross_income * tax_rate;
// prompt for and read the province id
prov_id = JOptionPane.showInputDialog("Please enter your province's two-letter abbreviation (e.g., AB for Alberta): ");
// prompt for and read the gross income
String answer = JOptionPane.showInputDialog("Please enter your taxable income: ");
//convert user input to folat
gross_income = Float.parseFloat(answer);
net_income=gross_income*(1-tax_rate);
tax_amount=gross_income*tax_rate;
rectMode(CENTER);
// Alberta
if ( prov_id.equals("AB") || prov_id.equals("ab"))
{
if (gross_income>=0&&gross_income<=40000)
{
tax_rate=0.25;
JOptionPane.showMessageDialog(frame,"Province: "+ prov_id + "\nGross Income: "+ gross_income + "\nTax Rate: "+ tax_rate+ "\nTax Amount: "+ tax_amount+"\nNet Income: "+ net_income);
}
}
The expected out put is supposed to be this: https://imgur.com/a/Gx2XOql
So far my code displays this: https://imgur.com/a/Gx2XOql
The window where the bar graphs are shown is Processing's not one from JOptionPane.showMessageDialog() since the window is named "TaxCalculator_kEY", which i assume is the name of the file, not "Message".
This is a loan calculator program. I'm having trouble with the math. Everything else seems to be correct except for the value of the beginning balance after 2 months. Notice that the beginning balance of the 3rd month is different from the ending balance of the 2nd month. Same thing for the succeeding months. I've been trying to fix it but everything didn't work out. I need them to be the same so the ending balance of the last month will be 0.
This is a sample output of the program:
Personal Loan Payment Calculator
Enter a loan amount: 1000
Enter the loan term (months): 6
Enter the interest rate (% per year): 9
Loan Payment and Amortization Table
Months Beginning Monthly Principal Interest Ending
Balance Payment Paid Paid Balance
1 1000.00 171.07 163.57 7.50 836.43
2 836.43 171.07 164.80 6.27 671.64
3 670.41 171.07 166.04 5.03 504.37
4 501.88 171.07 167.30 3.76 334.57
5 330.78 171.07 168.59 2.48 162.19
6 157.06 171.07 169.89 1.18 -12.83
Summary:
========
Loan Amount: $1,000.00
Monthly Payment: $171.07
Number of Payments: 6
Total Interest Paid: $24.00
Annual Interest Rate: 9.00%
This is the program:
public class LoanCalculator {
public static void main(String[] args) {
System.out.println("Personal Loan Payment Calculator"); // print the name of the program
System.out.println("================================");
Scanner keyboard = new Scanner (System.in); // define a Scanner object attached to a keyboard
String badInput; // assign non-integer or non-double inputs to badInput
System.out.print("Enter a loan amount: "); // prompt the user to enter loan amount
while ( ! keyboard.hasNextDouble()) // is the first input value a double?
{
badInput = keyboard.next();
System.out.println("Error: expected a Double, encountered: " + badInput);
System.out.println("Please enter a loan amount in Double: ");
}
double loanAmount = keyboard.nextDouble(); // assign the first input to loanAmount
System.out.print("Enter the loan term (months): "); // prompt the user to enter number of months
while ( ! keyboard.hasNextInt()) // is the second input value an int?
{
badInput = keyboard.next();
System.out.println("Error: expected an Integer, encountered: " + badInput);
System.out.println("Please enter a loan term in Integer: ");
}
int loanTerm = keyboard.nextInt(); // assign the second input to loanTerm
System.out.print("Enter the interest rate (% per year): "); // prompt the user to enter the interest rate
while ( ! keyboard.hasNextDouble()) // is the first input value a double?
{
badInput = keyboard.next();
System.out.println("Error: expected an integer, encountered: " + badInput);
System.out.println("Please enter a loan amount in Double: ");
}
double interestRate = keyboard.nextDouble(); // assign the third input to interestRate
System.out.println(); // skip a line
System.out.println(" Loan Payment and Amortization Table");
System.out.printf("%s", "=============================================================");
System.out.println();
System.out.printf("%5s %10s %10s %10s %10s %10s", "Months" ,"Beginning", "Monhtly", "Principal", "Interest", "Ending");
System.out.println();
System.out.printf(" %5s %10s %10s %10s %10s %10s", "#","Balance", "Payment", "Paid", "Paid", "Balance");
System.out.println();
System.out.printf("%s ", "=============================================================");
System.out.println();
double monthlyRate = (interestRate / 100.0) / 12.0;
double monthlyPayment = (monthlyRate * loanAmount) / ( 1 - (Math.pow( 1 + monthlyRate, - loanTerm)));
double beginningBalance = loanAmount;
double interestPaid = beginningBalance * monthlyRate;
double principalPaid = monthlyPayment - interestPaid;
int total_interest_paid = 0;
for (int monthCount = 0 ; monthCount < loanTerm ; ++monthCount)
{
int months = 1 + monthCount;
beginningBalance = loanAmount - principalPaid * monthCount;
interestPaid = beginningBalance * monthlyRate;
principalPaid = monthlyPayment - interestPaid;
double endingBalance = beginningBalance - principalPaid;
System.out.printf(" %5d %10.2f %10.2f %10.2f %10.2f %10.2f\n", months, beginningBalance, monthlyPayment, principalPaid, interestPaid, endingBalance);
total_interest_paid += interestPaid;
}
System.out.printf("%s ", "=============================================================");
System.out.println();
NumberFormat currency = NumberFormat.getCurrencyInstance();
DecimalFormat percentFormat = new DecimalFormat ("0.00");
System.out.println("\nSummary:");
System.out.println("========");
System.out.println("Loan Amount: " + currency.format(loanAmount));
System.out.println("Monthly Payment: " + currency.format(monthlyPayment));
System.out.println("Number of Payments: " + loanTerm);
System.out.println("Total Interest Paid: " + currency.format(total_interest_paid));
System.out.println("Annual Interest Rate: " + percentFormat.format(interestRate) + "%");
}
}
The error is very simple:
beginningBalance = loanAmount - principalPaid * monthCount;
Remember that "principalPaid" increases every month. The total principal paid is not the last principalPaid * mouthCount but the sum of the principal paid in all months.
You could create a running total for principalPaid like you did for interest paid.
But it would be much easier to do beginningBalance = previous month endingBalance.
I have the following simple sales program and am having trouble creating a restart loop around the program. My primary issue is converting the boolean from a string to a boolean type, I am getting an error in Eclipse that says, "The method parseBoolean(String) is undefined for the type Boolean".
However, I have defined a boolean variable at the top, boolean tryAgain = false;
and for some reason I cannot set the user input scanner to take the True or False value without an error. The error is occurring with the last line when I try to cast the nextLine from the user to boolean.
import java.util.Scanner;
public class Sales {
public static void main(String args[]) {
String item1, item2, item3; //Three vars for items
double price1, price2, price3; //Three vars for price
int quantity1, quantity2, quantity3; //Three vars for quantity
Scanner userInput = new Scanner(System.in); //Creates scanner for user input
double sum; //var for total before tax
double tax; //var for tax
double total; //var for total with tax
double tax_total; //var to calculate tax
boolean tryAgain = true; //boolean for try again loop to restart program
// First set of inputs
while (tryAgain) {
System.out.println("Please enter the first item: ");
item1 = userInput.nextLine();
System.out.println("Please enter the price of the first item: ");
price1 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity1 = userInput.nextInt();
// Second set of inputs
System.out.println("Please enter the second item: ");
item2 = userInput.next();
System.out.println("Please enter the price of the second item: ");
price2 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity2 = userInput.nextInt();
// Third set of inputs
System.out.println("Please enter the third item: ");
item3 = userInput.next(); //skipping over item 2. Why?
System.out.println("Please enter the price of the third item: ");
price3 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity3 = userInput.nextInt();
System.out.println("Please enter the sales tax rate: "); //Prompt user for tax rate
tax = userInput.nextDouble();
//Print line item totals
System.out.println("Line item totals");
System.out.println("____________________");
System.out.println("Item 1: " + item1 + "\t" + "$" + price1);
System.out.println("Item 2: " + item2 + "\t" + "$" + price2);
System.out.println("Item 3: " + item3 + "\t" + "$" + price3);
System.out.println();
//Process final output for display
sum = price1 + price2 + price3;
total = (sum * tax) + sum;
tax_total = tax * sum;
System.out.println("Total cost(no tax):\t" + "$" + sum); //display total cost witout tax
System.out.println("Total tax(" + tax + " rate): \t" + "$" + tax_total); //display total tax
System.out.println("Total cost(with tax):\t" + "$" + total); //display total with tax
System.out.println();
System.out.println("Program created by James Bellamy");
System.out.println("Do you want to run the program again? (True or False)");
tryAgain = Boolean.parseBoolean(userInput.nextLine());
}
}
}
The reason it gives you trouble is that when the user enters a double then hits enter, two things have just been entered - the double and a "newline" which is \n.
The method you are calling, "nextDouble()", only reads in the double, which leaves the newline in the input stream. But calling nextLine() does read in newlines, which is why you have to call nextLine() before your code would work.
Add this line before last line .
userInput.nextLine();
Well, I couldn't get it to work with a boolean for some reason, so I changed to a do while loop. Here is the final code. Also I did use the tip for clearing out the nextLine().
import java.util.Scanner;
public class Sales2 {
public static void main(String args[]) {
String item1, item2, item3; //Three vars for items
double price1, price2, price3; //Three vars for price
int quantity1, quantity2, quantity3; //Three vars for quantity
Scanner userInput = new Scanner(System.in); //Creates scanner for user inputjea
double sum; //var for total before tax
double tax; //var for tax
double total; //var for total with tax
double tax_total; //var to calculate tax
boolean tryAgain = true; //boolean for try again loop to restart program
// First set of inputs
String answer; //Define var type of String for do while loop to restart program
do { //Do this loop while string == (last line of code while loop)
System.out.println("Please enter the first item: ");
item1 = userInput.nextLine();
System.out.println("Please enter the price of the first item: ");
price1 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity1 = userInput.nextInt();
// Second set of inputs
System.out.println("Please enter the second item: ");
item2 = userInput.next();
System.out.println("Please enter the price of the second item: ");
price2 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity2 = userInput.nextInt();
// Third set of inputs
System.out.println("Please enter the third item: ");
item3 = userInput.next(); //skipping over item 2. Why?
System.out.println("Please enter the price of the third item: ");
price3 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity3 = userInput.nextInt();
System.out.println("Please enter the sales tax rate: "); //Prompt user for tax rate
tax = userInput.nextDouble();
//Print line item totals
System.out.println("Line item totals");
System.out.println("____________________");
System.out.println("Item 1: " + item1 + "\t" + "$" + price1);
System.out.println("Item 2: " + item2 + "\t" + "$" + price2);
System.out.println("Item 3: " + item3 + "\t" + "$" + price3);
System.out.println();
//Process final output for display
sum = price1 + price2 + price3;
total = (sum * tax) + sum;
tax_total = tax * sum;
System.out.println("Total cost(no tax):\t" + "$" + sum); //display total cost witout tax
System.out.println("Total tax(" + tax + " rate): \t" + "$" + tax_total); //display total tax
System.out.println("Total cost(with tax):\t" + "$" + total); //display total with tax
System.out.println();
System.out.println("Program created by James Bellamy");
System.out.println("Do you want to run the program again? (yes or no)"); //Prompt user for restart
userInput.nextLine(); //Clear scanner
answer = userInput.nextLine();
}
while (answer.equalsIgnoreCase("Yes")); //Connected to do while loop
//
}
}
Scanner supports nextBoolean(). Just use it:
tryAgain = userInput.nextBoolean()
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