java looping program cant detect symbols - java

I have a little issue with this program I am writing. When I run this with CMD it gives me a few errors such as the variable "totalFry" cant be defined even though it is a Global Variable. Any Help would be great, thank you very much!
(Note: this is my first time writing looping/ while code)
The idea is to give the user 3 choices, have the user input an option
(1-3) and have said options appear to prompt the user to input the
amount they want for said team.
Next, the program will ask the user
if they want to end the order, assuming they input "Yes" the program
will ask if the user wants to end the program if the user inputs
"yes" the program will go and total up the cost and display it.
End of program
Code:
import java.io.*;
import java.util.Scanner;
//Lab 4_5
public class Lab4_5 {
static Scanner keyboard = new Scanner(System.in);
// Declare local variables
static double totalBurger, totalFry, totalSoda;
static int option, burgerCount, fryCount, sodaCount;
// The main method
public static void main(String[] args) {
//Add a loop to run program again
String endProgram = "no";
while (endProgram.equals("no"))
//Add a loop to take in order
String endOrder = "no";
while (endOrder.equals("no"))
// Add statements to display the menu, get the user choice, and assign it to option
System.out.println("Enter 1 for Yum Yum Burger");
System.out.println("Enter 2 for Grease Yum Fires");
System.out.println("Enter 3 for Soda Yum");
//Add a Select Case statement based on the value of option
int option = 0;
option = keyboardnextInt();
//When option = 1
if (option == 1)
double totalBurger = 0;
int burgerCount = 0;
System.out.println("Enter the number of burgers you want ");
burgerCount = keyboard.nextDouble();
totalBurger = totalBurger + burgerCount * .99;
//When option = 2
if (option == 2)
double totalFry = 0;
int fryCount = 0;
System.out.println("Enter the number of fires you want ");
fryCount = keyboard.nextDouble();
totalFry = totalFry + fryCount * .79;
//When option = 3
if (option == 3)
double totalSoda = 0;
int sodaCount = 0;
System.out.println("Enter the number of sodas you want ");
sodaCount = keyboardnext.Double();
totalSoda = totalSoda + sodaCount * 1.09;
//Imput if user wants to end order
System.out.println("Do you want to end your order? (Enter no to add more items ) ");
endOrder = keyboard.next();
//Call
clacTotal();
printReceipt();
//Ask user if they want to end the program
System.out.println("Do you want to end the program? (Enter no to process a new order) ");
endProgram = keyboard.next();
}
//Calculate the total amount
public static void calcTotal() {
double total = 0;
double tax = 0;
double subtotal = 0;
//Add statements to calc total with tax and call printReceipt
calcTotal = totalBurger + totalFry + totalSoda * .06;
}
public static void printReceipt() {
//Add statements to display the total as shown above
System.out.println("Your total is $" + calcTotal);
}
}

Your code has many issues including the following:
missing curly braces on beginning and end of if's and loops
creating duplicate variables.
using keyboard.nextDouble() on ints
plus some spelling mistakes.
The following code should at least compile and work as you wanted.
import java.util.Scanner;
public class Lab4_5 {
static Scanner keyboard = new Scanner(System.in);
// Declare local variables
static double totalBurger, totalFry, totalSoda, calcTotal;
static int option, burgerCount, fryCount, sodaCount;
// The main method
public static void main(String[] args) {
//Add a loop to run program again
String endProgram = "no";
while (endProgram.equals("no")){
//Add a loop to take in order
String endOrder = "no";
while (endOrder.equals("no")){
// Add statements to display the menu, get the user choice, and assign it to option
System.out.println("Enter 1 for Yum Yum Burger");
System.out.println("Enter 2 for Grease Yum Fires");
System.out.println("Enter 3 for Soda Yum");
//Add a Select Case statement based on the value of option
int option = 0;
option = keyboard.nextInt();
//When option = 1
if (option == 1){
totalBurger = 0;
burgerCount = 0;
System.out.println("Enter the number of burgers you want ");
burgerCount = keyboard.nextInt();
totalBurger = totalBurger + burgerCount * .99;
}
//When option = 2
if (option == 2){
System.out.println("Enter the number of fires you want ");
fryCount = keyboard.nextInt();
totalFry = totalFry + fryCount * .79;
}
//When option = 3
if (option == 3){
System.out.println("Enter the number of sodas you want ");
sodaCount = keyboard.nextInt();
totalSoda = totalSoda + sodaCount * 1.09;
}
//Imput if user wants to end order
System.out.println("Do you want to end your order? (Enter no to add more items ) ");
endOrder = keyboard.next();
}
calcTotal();
printReceipt();
//Ask user if they want to end the program
System.out.println("Do you want to end the program? (Enter no to process a new order) ");
endProgram = keyboard.next();
}
}
//Calculate the total amount
public static void calcTotal() {
//Add statements to calc total with tax and call printReceipt
calcTotal = totalBurger + totalFry + totalSoda * .06;
}
public static void printReceipt() {
//Add statements to display the total as shown above
System.out.println("Your total is $" + calcTotal);
}
}

Related

Display bill total, Java public void display() error

I'm having some trouble executing the total bill display. I asked my professor who gave me this small block of code, which I modified to meet my needs, but for some reason it is not executing and has the error:
Illegal start to expression for line --> public void display().
The compiler also suggests to end with a semi colon which I don't believe is accurate.
What am I missing that public void display() is not being executed and is erroneous?
import java.util.Scanner;
public class CoffeeShop
{
/* Author:
Date:
Program: Create a Coffee Shop application that uses a while loop to build a customer order. The Coffee Shops sells coffee ($3.25), espresso ($4.25), and tea ($2.75). The coffee selection presents the customer with the choices of iced (no charge), cream (50 cents), and sugar (50 cents). The espresso selection presents the customer with choice of caramel (no charge) and chocolate (no charge) with one shot (no charge) or two shots ($1.25) of espresso. Once the customer is done, he or she will receive a bill of the total price. After each selection, the customer will have the choice of returning to the main menu for additional purchases. Use nested loops to handle customers' submenu selections.
*/
public static void main(String[] args)
{
//declarations
double coff = 3.25;
double esp = 4.25;
double tea = 2.75;
double cream = .50;
double sugar = .50;
double dblShot = 1.25;
int dblshotQty = 0;
int userInput = 0;
int userInput2 = 0;
int coffQty = 0;
int espQty = 0;
int teaQty = 0;
int creamQty = 0;
int sugarQty = 0;
double runTotal = 0;
double totalCoff = 0;
double totalEsp = 0;
double totalTea = 0;
double totalBill = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Would you like to place an order? press 1 for yes or 2 for no :");
//start a loop with a control variable asking if they would like a cup of coffee yes or no
userInput = scan.nextInt();
while(userInput == 1)
{
System.out.print("Enter 1 for Coffee, 2 for Espresso, or 3 for tea: ");
userInput2 = scan.nextInt();
switch(userInput2)
//if 1 is pressed coffee is ordered
{ // open switch
case '1':
{
coffQty = coffQty + 1;
System.out.print("Press 1 if you would like your coffee iced or 2 for no: ");
userInput = scan.nextInt();
}
{
System.out.print("Press 1 if you would like cream for $.50 or 2 for no: ");
userInput = scan.nextInt();
if ( userInput == 1 )
{
creamQty = creamQty + 1;
}
}
{
System.out.print("Press 1 if you would like sugar for $.50 or 2 for no: ");
userInput = scan.nextInt();
if ( userInput == 1 )
{
sugarQty = sugarQty + 1;
}
}//end case 1
break;
// espresso is ordered ask for double shot
case '2':
{
espQty = espQty +1;
System.out.println("Press 1 for a double shot for $1.25 or 2 for no: ");
userInput = scan.nextInt();
if(userInput == 1)
{
dblshotQty = dblshotQty +1;
}
}//end case 2
break;
//tea is ordered
case '3':
{
teaQty = teaQty + 1;
System.out.println("You have selected tea! Great Choice.");
}//end case 3
}//end switch
// create output display for total bill adding all totals
public void display()
{
double totalCoff = coffQty * coff + cream * creamQty + sugar * sugarQty;
double totalEsp = espQty * esp + dblshot * dblshotQty;
double totalTea = teaQty * tea;
System.out.println("Order: \n "+coffQty + " Coffee"
+ "\n "+creamQty +" Cream"
+ "\n "+sugarQty + " Sugar"
+ "\nTotal Coffee: "+ totalCoff);
System.out.println(" "+teaQty + " Tea"
+ "\nTotal Tea: "+ totalTea);
System.out.println(" "+espQty + " Espresso"
+ "\n "+dblshotQty +" Double shot"
+ "\nTotal Espresso: "+ totalEsp);
double totalBill = totalCoff+totalEsp+totalTea;
System.out.println("\nTotal drink order: "+totalBill);
}
break;
} // end while
}
} // end of class
Your code structure is making things difficult for you. As mentioned by #Carcigenicate, (nice name btw), you have you declared a method inside the main method. Once you change that, you'll notice now that now the display method shows compiler errors. This is because the variables referenced in display are no longer visible. You have a few options:
Rethink the design of the class i.e What methods should exist and how they will be called.
Take the display method outside the main method and then make the variables member variables that are visible to the methods you need. Read about the effects of using member variables first.
Remove the display method completely and move the logic to the main method.
I see a few main problems:
You defined display inside of main, inside of a while loop. You can't define methods inside of methods, let alone inside of loops. Move display outside of main, but still inside the class.
You have a misplaced break floating around under display. Get rid of that, as that will also be an error.
As #MiiinimalLogic pointed out, you're relying on data from main inside of display. You'll need to pass the data from main to display as arguments.

Non-gui checkout register menu: how to format it?

I'm stumped on how to format my menu. What I have so far isn't working but I know it could be better formatted and shorter. This is the description of the assignment. You can see that my approach isn't going to work but I don't know how to change my approach...
I'm pretty sure I need to use arrays but I'm not sure how to store a public array so any method can call and store information to it.
import java.util.Scanner;
/*
#author David Jacobsen
#version 10-23-16
*/
/*
CODE DESIGN:
-> Bring menu from basicMenu assingment [X]
-> Adapt for this assignment [X]
-> Add content for new menu style []
-> Adapt loop position from basicMenu []
-> Add interior loops []
-> Capitalize class name for *proper grammer* [X]
For Display Cart have three seperate totals for each item then divide by each total by its respective items total
to find the number of that item the customer has purchased and assign it to a varible to be added into menu print out.
For Print Recipt have the system call 'display cart' and add a subtotal, tax, and total printer to the end.
Loop with basic menu while looper. (method 'startOver').
*/
public class CheckoutCounter {
public static void main(String[] args) {
while (startOver() == true) {
//Define Menu Bins
//Top Menu Choice Printer
System.out.println("1. Purchase Items");
System.out.println("2. Display Cart");
System.out.println("3. Print Your Recipt");
System.out.println(" ");
//Choose 1, 2, or 3 Menu Input
double doubleA;
Scanner topMenu = new Scanner(System.in);
System.out.print("Please select and option, 1 - 3:");
doubleA = topMenu.nextDouble();
System.out.println(" ");
System.out.println("Good choice.");
System.out.println(" ");
//Method Chooser
//Menu Choice "Purchase Items"
if (doubleA <= 1) {
priceTotalDragonfruit = priceTotalDragonfruit + CheckoutCounter.purchaseItems();
}
//Menu Choice "Print Recipt"
else if (doubleA >= 3) {
CheckoutCounter.printRecipt();
}
//Menu Choice "Display Cart"
else {
CheckoutCounter.displayCart();
}
}
}
//Purchase Items Method
public static double purchaseItems() {
//Define Variables and Initialize
double dragonfruit = 5.99;
double organicBlasphemy = 99.99;
double dayOldAnswerToTheUniverse = 100000;
double total = 0;
double multiplier;
//Define Total Containers and Initialize
double priceTotalDragonfruit = 0;
double priceTotalOrganicBlasphemy = 0;
double priceTotaldayOldAnswerToTheUniverse = 0;
//Top Menu Choice Printer
System.out.println("1. Dragonfruit ($5.99/lb)");
System.out.println("2. Organic Blasphemy ($99.99 per comment)");
System.out.println("3. 1 Day Old Answer to the Universe ($100,000 per request)");
System.out.println(" ");
//Choose 1, 2, or 3 Menu Input
double doubleA;
Scanner topMenu = new Scanner(System.in);
System.out.print("Please select and option, 1 - 3:");
doubleA = topMenu.nextDouble();
System.out.println(" ");
System.out.println("Good choice.");
System.out.println(" ");
//Method Chooser
//Menu Choice "Dragonfruit"
if (doubleA <= 1) {
System.out.println("How much/many do you want?");
Scanner multiplierScanner = new Scanner(System.in);
System.out.println("Enter amount here:");
multiplier = multiplierScanner.nextDouble();
System.out.println("We added your item(s) to your cart.");
priceTotalDragonfruit = total + (5.99 * multiplier);
}
//Menu Choice "1 Day Old Answer to the Universe"
else if (doubleA >= 3) {
System.out.println("How much/many do you want?");
Scanner multiplierScanner = new Scanner(System.in);
System.out.println("Enter amount here:");
multiplier = multiplierScanner.nextDouble();
System.out.println("We added your item(s) to your cart.");
priceTotaldayOldAnswerToTheUniverse = total + (100000 * multiplier);
}
//Menu Choice "Organic Blasphemy"
else {
System.out.println("How much/many do you want?");
Scanner multiplierScanner = new Scanner(System.in);
System.out.println("Enter amount here:");
multiplier = multiplierScanner.nextDouble();
System.out.println("We added your item(s) to your cart.");
priceTotalOrganicBlasphemy = total + (99.99 * multiplier);
}
}
//Display Cart Method
public static void displayCart() {
}
//Print Recipt/End Program Method
public static void printRecipt() {
}
//Start Over Loop Method
public static boolean startOver() {
Scanner inputScanner = new Scanner(System.in);
System.out.print("Please enter either 'True', to continue, or 'False', to stop: ");
Boolean userInputA;
userInputA = inputScanner.nextBoolean();
boolean goAhead;
if (userInputA == false) {
goAhead = false;
}
else {
goAhead = true;
}
return goAhead;
}
}
This is actually a good exercise for a student like you. I wont give you the exact answer (there are many ways though) but let me help you analyze this.
Java is an OOP language. The first thing to do is always determine what your domain objects would be.
Based on your requirement, it is asking for a Menu and create a method for each of the things it does. (sounds like an Object, yes?)
It should look something like below:
public class Menu{
public void purchaseItems(){ // pass an argument or return something depending on what you need
// figure out how you purchase items
}
public void displayCurrentPurchases(){
// figure out how you display the cart (your cart can be a List, Map, or even a class)
}
public void printReceipt(){
// figure out how you print the receipt
//somewhere here you would need to call your computeTaxes method
double netAmount = computeTaxes(grossAmount);
}
/* It's a good idea to limit a method to doing only one thing as much as possible, so you might need to make private methods such as computing for taxes below */
private double computeTaxes(double totalAmount){
return total * 0.098;
}
// and so on...
}
Now that you've got your Menu object set, you can create your Main class to actually create an instance of your Menu:
public class MainClass{
public static void main(String[] args) {
Menu menu = new Menu();
/* create your scanner here, and call the methods on the Menu depending on the user's choice */
// a switch for the user's selection might be a good idea:
switch(selected){
case 1:
menu.purchaseItems();
break;
case 2:
// you get the point. I leave this to you.
default:
sysout("Invalid selection");
break;
}
}
}

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 can I restart my java program based on user input?

I'm writing a program used to calculate the total sales of employees in a small business, and am trying to figure out how to restart the program based on a user input of y/n. I know that loops are what I need to use here, but need a push in the right direction.
Code:
import java.util.Scanner;
public class calcMain {
public static void main(String[]args){
double totalPay = 0, itemOne = 239.99, itemTwo = 129.75, itemThree = 99.95, itemFour = 350.89, commission;
int weeklyBonus = 200, numSold;
String employee1, employee2, employee3, employee4, yn;
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the salesperson's name: ");
employee1 = kb.nextLine();
System.out.println("Please enter the number of Item 1 sold: ");
numSold = kb.nextInt();
totalPay += (itemOne * numSold);
System.out.println("Please enter the number of Item 2 sold: ");
numSold = kb.nextInt();
totalPay += (itemTwo * numSold);
System.out.println("Please enter the number of item 3 sold: ");
numSold = kb.nextInt();
totalPay += (itemThree * numSold);
System.out.println("Please enter the number of item 4 sold: ");
numSold = kb.nextInt();
totalPay += (itemFour * numSold);
System.out.println("The total weekly earnings for " +employee1+ " are: " +totalPay);
System.out.println("Would you like to input the sales of another employee? (y/n)");
yn = kb.next();
}
}
Put all the code inside a while loop that says while (yn.equalsIgnoreCase("y"))
Don't forget to initialize yn to y!
Second solution:
Modify the code so that it returns a string, and if the user inputs y, return y, or if the user inputs n, return n.
Put all that code inside a method (lets call it method x for now)
public static void main(String[] args) {
while(x().equalsIgnoreCase("y")){}
}
Using a do-while loop (while loop should have the same effect) and ask for (y/n) at the end.
Like this:
String yn;
do
{
// Your code here
// Ask for confirmation
}
while (yn.equals("y"));

Counter won't work to end loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am working on an assignment and it is working well so far. But several aspects aren't working. For starters, my counters for int total and int counter won't work. Also my if statements don't seem to be working. I have been scratching my head for several days now.
The assignment calls for a program to input the order number and will loop based on how many orders the customer has. It also calls for customer name, sign type(wood or plastic), the number of characters,and color of characters.
Some more information:
The base price for all signs is $20.
If sign is wood, add $10. If it is plastic add $5.
The first 5 letters/numbers are included in base price, and $2 for each additional character.
Black or white characters are included in base price, there is an additional $8 for colored letters.
If the total charge is more than $100 give 25% discount on total price.
Here is my code right now:
import java.util.Scanner;
public class Carpenter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int orderNumber;
String custName;
String signType;
int numOfCharacters;
String color;
int i = 20;
double total;
int counter;
System.out.println("Enter your order number");
orderNumber = sc.nextInt();
counter=orderNumber;
counter--;
sc.nextLine();
System.out.println("Enter customer name");
custName = sc.next();
do{
System.out.println("Enter the sign type (wood or plastic)");
signType = sc.next();
if(signType == "wood") {
i+=10;
}
if(signType == "plastic") {
i+=5;
}
System.out.println("Enter the number of characters");
numOfCharacters = sc.nextInt();
if(numOfCharacters > 5) {
i += 2*(numOfCharacters-5);
}
System.out.println("Enter the color of characters");
color = sc.next();
if(color != "white" || color != "black") {
i += 8;
}
total= i;
System.out.println("Total is: $" + total);
if( total > 100 ) {
total = (total * 0.25);
System.out.println("The total is " + total );
}
}
while(counter <= orderNumber);
}
}
I added comments to guide you through the changes I made. Also, remember to call the sc.NextLine() function after you get user input so that they can input something different next time (this is called 'flushing' the buffer).
import java.util.Scanner;
public class Carpenter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int orderNumber;
String custName;
String signType;
int numOfCharacters;
String color;
int i = 20;
double total;
int counter;
//I changed the phrasing just because it is a little confusing
System.out.println("Enter your number of orders");
orderNumber = sc.nextInt();
counter = orderNumber;
sc.nextLine();
System.out.println("Enter customer name");
custName = sc.next();
sc.nextLine();
//When you know how many times you want to repeat something (like when a user tells you how many) I prefer using a for-loop, a do while loop works as well though
for(int x=0; x<counter;x++)
{
System.out.println("Enter the sign type (wood or plastic)");
signType = sc.next();
//When comparing Strings, there is a function that you can use to compare them rather than using '=='
// It is also good to use the 'equalsIgnoreCase()' function to be more user friendly and robust
if(signType.equalsIgnoreCase("wood")) {
i+=10;
}
if(signType.equalsIgnoreCase("plastic")) {
i+=5;
}
//Flush the buffer (I haven't tested if this is necessary or not, it is good practice though)
sc.nextLine();
System.out.println("Enter the number of characters");
numOfCharacters = sc.nextInt();
if(numOfCharacters > 5) {
i += 2*(numOfCharacters-5);
}
System.out.println("Enter the color of characters");
color = sc.next();
//Same concept as above, the differene is the ! before the function to test if it is false or not
if(!color.equalsIgnoreCase("white") || !color.equalsIgnoreCase("black")) {
i += 8;
}
}
total = i;
//You will not want to print this out until the end due to the possibility of it being over $100
// System.out.println("Total is: $" + total);
if( total > 100 ) {
//Mathematically speaking, you are making your total a quarter of what the original is, rather than taking a quarter off. You want 75% rather than 25%
// total = (total * 0.25);
total = (total * 0.75);
}
System.out.println("Total is: $" + total);
}
}
You should set counter to the correct starting value (which is presumably 1 in your case):
orderNumber = sc.nextInt();
counter=1;
//counter=orderNumber;
//counter--;
Then at the end of the loop, you should increment your counter:
do{
//code
counter++;
}
while(counter <= orderNumber);

Categories

Resources