I'm trying to make a virtual store program. Synopsis is if at any time the user enters 'q', the program should quit.
Once the user enters 'c', ask the user to enter a 2-character state such as CA, NV, WA. If a code other
than these three is entered, it falls under "other". Then display what is in their cart and the calculated
total price based on discounts and include the tax.
The problem is that the program would ask user for item and quantity once, then it goes into checkout mode. Whenever I put 'q', it goes to the next line.
Here is the code:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Random;
import java.io.*;
public class virtualStore {
public static void main(String [] args) throws IOException{
/* If the user enters an item number, the program should ask the user to enter how many of that item
they want, and then print the menu again. If at any time the user enters 'q', the program should quit.
Once the user enters 'c', ask the user to enter a 2-character state such as CA, NV, WA. If a code other
than these three is entered, it falls under "other". Then display what is in their cart and the calculated
total price based on discounts and include the tax. You should use the Math.round() and
System.out.printf methods to round numbers and to display to 2 decimal places. */
Scanner keyboard = new Scanner (System.in);
String input;
char c = ' ';
char q = ' ';
//tax rates
double CAtaxRate = .09;
double NVtaxRate = .07;
double WAtaxRate = .065;
double other = .06;
double tax = 0;
//checkout
double checkout = 0;
double total;
double cash = 0;
double change = 0;
//items
double mushrooms = 0.3;
double onions = 0.6;
double watermelon = 2.5;
double cookies = 1;
int item = 0;
//number of items
int numMushrooms = 0;
int numOnions = 0;
int numWatermelon = 0;
int numCookies = 0;
DecimalFormat dollar = new DecimalFormat("#,##0.00");
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to Alex's Store."
+ " Here is the menu. "
+ "\nEnter the item number to add it to your cart,"
+ " enter \'c\' to checkout or \'q\' to quit. ");
while(true)
//while(c != 'c' && c != 'q')
{
for (item = 1; item < 4; item ++){
System.out.println("Item\t\t\tPrice\t\t\tQuantity");
System.out.println("---------------------------------------------------------");
System.out.println("1. Mushrooms\t\t($0.30/$0.25)\t\t" + numMushrooms);
System.out.println("2. Onions\t\t($0.60/$0.50)\t\t" + numOnions );
System.out.println("3. Watermelon\t\t($2.50/$2.00)\t\t" + numWatermelon);
System.out.println("4. Cookies\t\t($1.00/$0.75)\t\t" + numCookies);
System.out.println("---------------------------------------------------------");
System.out.println("Enter item number between 1 through 4");
System.out.println("or enter 'c' for checkout or 'q' for quit.");
input = keyboard.nextLine();
item = Integer.parseInt(input);
if (input.equals("1"))
{
System.out.println("Enter how many items you want.");
String m = keyboard.nextLine();
numMushrooms = Integer.parseInt(m);
}
else if (input.equals("2"))
{
System.out.println("Enter how many items you want.");
String o = keyboard.nextLine();
numOnions = Integer.parseInt(o);
}
else if (input.equals("3"))
{
System.out.println("Enter how many items you want.");
String w = keyboard.nextLine();
numWatermelon = Integer.parseInt(w);
}
else if(input.equals("4"))
{
System.out.println("Enter how many items you want.");
String co = keyboard.nextLine();
numCookies = Integer.parseInt(co);
}
}
if (numMushrooms > 10)
{
mushrooms = 0.25;
}
else if (numOnions > 10)
{
onions = 0.5;
}
else if (numWatermelon > 10)
{
watermelon = 2;
}
else if (numCookies > 10)
{
cookies = .75;
}
// quit option
String quit = scanner.nextLine();
q = quit.charAt(0);
if (quit.equalsIgnoreCase("q"))
{
System.out.println("Goodbye");
scanner.close();
System.exit(0);
}
// checkout option
String ch = scanner.nextLine();
c = ch.charAt(0);
if (ch.equalsIgnoreCase("c"))
{
//checkout
checkout = numMushrooms * mushrooms + numOnions * onions + numWatermelon * watermelon + numCookies * cookies;
//tax
total = tax * checkout + checkout;
System.out.print("Enter state abbreviations: ");
input = keyboard.nextLine();
PrintWriter outputfile = new PrintWriter("receipt.txt");
outputfile.println("Your cart: ");
outputfile.println("Sub total:$ " + dollar.format(checkout));
if (input.equalsIgnoreCase("CA"))
{
total = CAtaxRate * checkout + checkout;
outputfile.println("Tax Rate: " + CAtaxRate);
outputfile.println("Tax: $" + dollar.format(CAtaxRate * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
else if (input.equalsIgnoreCase("NV"))
{
total = NVtaxRate * checkout + checkout;
outputfile.println("Tax Rate: " + NVtaxRate);
outputfile.println("Tax: $" + dollar.format(NVtaxRate * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
else if (input.equalsIgnoreCase("WA"))
{
total = WAtaxRate * checkout + checkout;
outputfile.println("Tax Rate: " + WAtaxRate);
outputfile.println("Tax: $" + dollar.format(WAtaxRate * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
else if (input.equalsIgnoreCase(input))
{
total = other * checkout + checkout;
outputfile.println("Tax Rate: " + other);
outputfile.println("Tax: $" + dollar.format(other * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
outputfile.println("-----------------------------------------------------");
input = keyboard.nextLine();
cash = Integer.parseInt(input);
outputfile.println("Enter amount of cash: $" + dollar.format(cash));
change = cash - total;
outputfile.println("Change due: $" + dollar.format(change));
outputfile.println("Thank you for shopping at Alex's store!");
outputfile.close();
FileWriter fw = new FileWriter("receipt.text", true);
PrintWriter pw = new PrintWriter(fw);
pw.println("C:\\Desktop\\Receipt.txt ");
pw.close();
}
}
}
}
You're using the wrong model to get user input.
Try doing something that looks like:
while(true) {
// Print the menu messages
String input = scanner.readLine();
if(input.equals("c")) {
// Read in and handle state abbreviation
} else if(input.equals("q")) {
System.exit(0);
} else {
int itemNumber = Integer.parseInt(input);
// Parse and handle item number
}
}
Related
I'm trying to compare the cost of a user's phone usage under plans from three
different providers. I can get as far as entering the usage details but once entered I try to call the method to rerun from the if statement but it just displays the main menu again and stops. I want it to run through the entire if statement from the start again
import java.util.Scanner;
public class MainMenuSelection {
public static int menuSel() {
int menuSel ;
System.out.println("ENTER USAGE DETAILS MENU\n");
System.out.println("Please select an option from the menu:");
System.out.println("1.Phone Call");
System.out.println("2.SMS ");
System.out.println("3.Data usage");
System.out.println("4. Return to main menu");
Scanner in = new Scanner(System.in);
System.out.println("Enter selection: ");
menuSel = in.nextInt();
while (menuSel < 1 || menuSel >4){
System.out.println("Value must bebetween 1 and 4, plese try again.");
System.out.println("Enter your selection: ");
menuSel = in.nextInt();
}
return menuSel;
}
public static int mainMenuSelection() {
System.out.println("MAIN MENU\n");
System.out.println("Please select from the menu:");
System.out.println("1. Enter Usage details");
System.out.println("2. Display Cost under provider 1");
System.out.println("3. Display Cost under provider 2");
System.out.println("4. Display Cost under provider 3");
System.out.println("5. Clear usage details");
System.out.println("6. Exit System");
int mainMenuSelection;
Scanner userInput = new Scanner(System.in);
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
//return mainMenuSelection;
while (mainMenuSelection < 1 || mainMenuSelection >6){
System.out.println("Value must bebetween 1 and 6, plese try again.");
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
}
System.out.println("You chose selection " + mainMenuSelection + "\n");
return mainMenuSelection;
}
public static void main(String[] args) {
System.out.println("Hello World!");
int callLength = 0;
int numSMS = 0;
int numberOfMB = 0;
int numberofCalls;
int callTime;
int totalcallTime = 0;
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
int menuSel = menuSel();
if (menuSel == 1) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of phone call you have made? ");
numberofCalls = in.nextInt();
for (int i = 0; i < numberofCalls; i++) {
Scanner callInput = new Scanner(System.in);
System.out.println("How long was the call in seconds?");
callTime = callInput.nextInt();
totalcallTime = callTime + totalcallTime;
}
System.out.println("Your total number of calls is " + numberofCalls);
System.out.println("Your total call time is " + totalcallTime + " seconds" + "\n");
} else if (menuSel == 2) {
System.out.println("Enter the number of SMS messages: ");
//int numSMS;
Scanner userNumSMS = new Scanner(System.in);
numSMS = userNumSMS.nextInt();
System.out.println("Your number of SMSs is " + numSMS + "\n");
} else if (menuSel == 3) {
System.out.println("Enter the amount of data in MB: ");
//int numberOfMB;
Scanner userNumMB = new Scanner(System.in);
numberOfMB = userNumMB.nextInt();
System.out.println("Your amount of data in MB is " + numberOfMB + "\n");
} else {
mainMenuSelection(); // go back to main menu
}
} else if (mainMenuSelection == 2) {
//Display cost under provider 1
double callCost = 0.03 * totalcallTime;
double smsCost = 0.10 * numSMS;
double dataCost = 0.02 * numberOfMB;
double totalCostProvider1 = callCost + smsCost + dataCost;
System.out.println(totalCostProvider1);
} else if (mainMenuSelection == 3) {
//Display cost under provider 2
double callCost2 = 0.04 * totalcallTime;
double smsCost2 = 0.12 * numSMS;
double dataCost2 = 0.04 * numberOfMB;
double totalCostProvider2 = callCost2 + smsCost2 + dataCost2;
System.out.println(totalCostProvider2);
} else if (mainMenuSelection == 4) {
//Display cost under provider 3
double callCost3 = 0.05 * totalcallTime;
double smsCost3 = 0.11 * numSMS;
double dataCost3 = 0.03 * numberOfMB;
double totalCostProvider3 = callCost3 + smsCost3 + dataCost3;
System.out.println(totalCostProvider3);
} else if (mainMenuSelection == 5) {
//clear usage details
} else {
System.out.println("Exiting System");
System.exit(0);
}
mainMenuSelection = mainMenuSelection();
}
}
Codes run from top to bottom. Therefore, after the int mainMenuSelection = mainMenuSelection(); and the if-else statement is run, the code would run once again for the mainMenuSelection = mainMenuSelection() and ends, as there is nothing left in the block.
A fairly simple solution would be using a while or do-while loop with a boolean checking if the user entered the number 6 to exit the system.
You can try this example:
public static void main(String[] args) {
/*
* Your variables here
*/
boolean isExit = false;
while(!isExit) {
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
// menuSel codes here
} else if (mainMenuSelection == 2) {
// Display cost under provider 1
} else if (mainMenuSelection == 3) {
// Display cost under provider 2
} else if (mainMenuSelection == 4) {
// Display cost under provider 3
} else if (mainMenuSelection == 5) {
// Clear usage details
} else {
System.out.println("Exiting System");
isExit = true;
}
}
Hopes this answer helps you well.
It looks like you need a loop. Your main method has an exit condition so you can essentially loop forever by wrapping the code in your main method with a while loop:
public static void main(String[] args) {
while(true) {
// your main method code in here
}
}
By the way, you need to edit your code above in good formatting.
I have added a while loop in your main. Also, whenever any unwanted number the loop will exit using a break; and that in turn stops the program.
mainMenuSelection = mainMenuSelection();
I have deleted the above line from the code so you just need to call it once at the beginning of the code.
Let me know if you need sth else!
import java.util.Scanner;
public class MainMenuSelection {
public static int menuSel() {
int menuSel;
System.out.println("ENTER USAGE DETAILS MENU\n");
System.out.println("Please select an option from the menu:");
System.out.println("1.Phone Call");
System.out.println("2.SMS ");
System.out.println("3.Data usage");
System.out.println("4. Return to main menu");
Scanner in = new Scanner(System.in);
System.out.println("Enter selection: ");
menuSel = in.nextInt();
while (menuSel < 1 || menuSel > 4) {
System.out.println("Value must bebetween 1 and 4, plese try again.");
System.out.println("Enter your selection: ");
menuSel = in.nextInt();
}
return menuSel;
}
public static int mainMenuSelection() {
System.out.println("MAIN MENU\n");
System.out.println("Please select from the menu:");
System.out.println("1. Enter Usage details");
System.out.println("2. Display Cost under provider 1");
System.out.println("3. Display Cost under provider 2");
System.out.println("4. Display Cost under provider 3");
System.out.println("5. Clear usage details");
System.out.println("6. Exit System");
int mainMenuSelection;
Scanner userInput = new Scanner(System.in);
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
//return mainMenuSelection;
while (mainMenuSelection < 1 || mainMenuSelection > 6) {
System.out.println("Value must bebetween 1 and 6, plese try again.");
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
}
System.out.println("You chose selection " + mainMenuSelection + "\n");
return mainMenuSelection;
}
public static void main(String[] args) {
int callLength = 0;
int numSMS = 0;
int numberOfMB = 0;
int numberofCalls;
int callTime;
int totalcallTime = 0;
while (true) {
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
int menuSel = menuSel();
if (menuSel == 1) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of phone call you have made? ");
numberofCalls = in.nextInt();
for (int i = 0; i < numberofCalls; i++) {
Scanner callInput = new Scanner(System.in);
System.out.println("How long was the call in seconds?");
callTime = callInput.nextInt();
totalcallTime = callTime + totalcallTime;
}
System.out.println("Your total number of calls is " + numberofCalls);
System.out.println("Your total call time is " + totalcallTime + " seconds" + "\n");
} else if (menuSel == 2) {
System.out.println("Enter the number of SMS messages: ");
//int numSMS;
Scanner userNumSMS = new Scanner(System.in);
numSMS = userNumSMS.nextInt();
System.out.println("Your number of SMSs is " + numSMS + "\n");
} else if (menuSel == 3) {
System.out.println("Enter the amount of data in MB: ");
//int numberOfMB;
Scanner userNumMB = new Scanner(System.in);
numberOfMB = userNumMB.nextInt();
System.out.println("Your amount of data in MB is " + numberOfMB + "\n");
}
} else if (mainMenuSelection == 2) {
//Display cost under provider 1
double callCost = 0.03 * totalcallTime;
double smsCost = 0.10 * numSMS;
double dataCost = 0.02 * numberOfMB;
double totalCostProvider1 = callCost + smsCost + dataCost;
System.out.println(totalCostProvider1);
} else if (mainMenuSelection == 3) {
//Display cost under provider 2
double callCost2 = 0.04 * totalcallTime;
double smsCost2 = 0.12 * numSMS;
double dataCost2 = 0.04 * numberOfMB;
double totalCostProvider2 = callCost2 + smsCost2 + dataCost2;
System.out.println(totalCostProvider2);
} else if (mainMenuSelection == 4) {
//Display cost under provider 3
double callCost3 = 0.05 * totalcallTime;
double smsCost3 = 0.11 * numSMS;
double dataCost3 = 0.03 * numberOfMB;
double totalCostProvider3 = callCost3 + smsCost3 + dataCost3;
System.out.println(totalCostProvider3);
} else if (mainMenuSelection == 5) {
//clear usage details
} else {
System.out.println("Exiting System");
System.exit(0);
break;
}
}
}
}
How would I make it to where I wanted my code to loop if any character besides n or N was entered? So if the user inputs a, t, w, g, etc., it would return back to the beginning of the current loop. I'm usin an if/else if loop. (Just messing around with NetBeans).
import java.util.Scanner;
public class InvoiceApp
{
public static void main(String[] args)
{
// welcome the user to the program
System.out.println("Welcome to the Invoice Total Calculator");
System.out.println(); // print a blank line
// create a Scanner object named sc
Scanner sc = new Scanner(System.in);
// perform invoice calculations until choice isn't equal to "y" or "Y"
String choice = "y";
if (choice.equalsIgnoreCase("y"))
{
// get the invoice subtotal from the user
System.out.print("Enter subtotal: ");
double subtotal = sc.nextDouble();
// calculate the discount amount and total
double discountPercent= 0.0;
if (subtotal >= 200)
discountPercent = .2;
else if (subtotal >= 100)
discountPercent = .1;
else
discountPercent = 0.0;
double discountAmount = subtotal * discountPercent;
double total = subtotal - discountAmount;
// display the discount amount and total
String message = "Discount percent: " + discountPercent + "\n"
+ "Discount amount: " + discountAmount + "\n"
+ "Invoice total: " + total + "\n";
System.out.println(message);
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
else if (choice.equalsIgnoreCase("n"));
}
}
}
Use a while(!(choice.equalsIgnoreCase("n"))) instead of your current if statement. You won't need an else section.
I want to use words instead of typing numbers. It's for someone who wants to order a food on a menu.
This is my output:
2
Good Salad $7.00
3
Soda $2.00
5
I just want to type Good Salad and go to the next line and so on. How do i fix this?
This is the rest of the code:
import java.util.Scanner;
import java.text.DecimalFormat;
public class Project1 {
public static void main(String[] args) {
int choice = 0;
boolean doneOrdering = false;
boolean yes = false;
String order, A, B;
Scanner Keyboard = new Scanner(System.in);
DecimalFormat moneyFormat = new DecimalFormat("$#,###.00");
double num, GoodBurger = 0, GoodSalad = 0, Soda = 0, KidsMeal = 0;
double GoodBurgers = 7.75;
double GoodSalads = 7.00;
double Sodas = 2.00;
double KidsMeals = 3.00;
double tax;
double subtotal = 0, total;
int C = 0;
double tip = 0.010;
final double salestax = 0.081;
System.out.println("Welcome to Good Burger!");
System.out.println("=======================");
System.out
.println("Place your orders and type 'Finish' when you are done");
System.out
.println("--------------------------------------------------------");
System.out.println("1. GoodBurger $8.00");
System.out.println("2. GoodSalad $ 7.00");
System.out.println("3. Soda $2.00");
System.out.println("4. KidsMeal $3.00");
System.out.println("Type '5' if you want to tip. \n");
System.out.println("What would you like?");
while (!doneOrdering) {
choice = Keyboard.nextInt();
if (choice == 1) {
System.out.println("GoodBurger $8.00");
subtotal = subtotal + 8.00;
} else if (choice == 2) {
System.out.println("Good Salad $7.00");
subtotal = subtotal += 7.00;
} else if (choice == 3) {
System.out.println("Soda $2.00");
subtotal = subtotal + 2.00;
} else if (choice == 4) {
System.out.println("KidsMeal $3.00");
subtotal = subtotal + 3.00;
} else if (choice == 5) {
doneOrdering = true;
System.out.println("Do you want to tip?");
A = Keyboard.next();
if (A.equalsIgnoreCase("yes")) {
System.out.print("What percentage would you like to tip? ");
C = Keyboard.nextInt();
double tiptotal = C * tip * subtotal;
double taxtotal = subtotal * salestax;
System.out.println("SubTotal $" + subtotal);
System.out.println("Tax " + salestax);
System.out.println("Tip $" + tiptotal);
System.out.println("-------------------------");
System.out.println(subtotal + tiptotal + taxtotal);
}
if (A.equalsIgnoreCase("no")) {
double tiptotal = C * tip * subtotal;
double taxtotal = subtotal * salestax;
System.out.println("SubTotal $" + subtotal);
System.out.println("Tax " + salestax);
System.out.println(subtotal + tiptotal + taxtotal);
}
} else
System.out.println("Invalid");
}
}
}
This example uses an HashMap to record prices:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Project1 {
private static String userMessage() {
StringBuffer buffer = new StringBuffer();
String lineSeparator = System.getProperty("line.separator");
buffer.append("Welcome to Good Burger!");
buffer.append(lineSeparator);
buffer.append("=======================");
buffer.append(lineSeparator);
buffer.append("Place your orders and type 'Finish' when you are done");
buffer.append(lineSeparator);
buffer.append("--------------------------------------------------------");
buffer.append(lineSeparator);
buffer.append("1. GoodBurger $8.00");
buffer.append(lineSeparator);
buffer.append("2. GoodSalad $ 7.00");
buffer.append(lineSeparator);
buffer.append("3. Soda $2.00");
buffer.append(lineSeparator);
buffer.append("4. KidsMeal $3.00");
buffer.append(lineSeparator);
buffer.append("Type '5' if you want to tip. \n");
buffer.append(lineSeparator);
buffer.append("What would you like?");
buffer.append(lineSeparator);
return buffer.toString();
}
private static Map<String, Double> getPrices() {
Map<String, Double> prices = new HashMap<String, Double>();
prices.put("GoodBurgers", 7.75);
prices.put("GoodSalads", 7.00);
prices.put("Sodas", 2.00);
prices.put("KidsMeals", 3.00);
return prices;
}
public static void main(String[] args) {
String choice;
boolean doneOrdering = false;
String tipConfirmation;
Scanner Keyboard = new Scanner(System.in);
double subtotal = 0;
int C = 0;
double tip = 0.010;
final double salestax = 0.081;
String userMessage = userMessage();
System.out.println(userMessage);
Map<String, Double> prices = getPrices();
while (!doneOrdering) {
choice = Keyboard.next();
if (prices.containsKey(choice)) {
double price = prices.get(choice);
System.out.println(choice + " " + price);
subtotal = subtotal + price;
} else if (choice == "Tip") {
doneOrdering = true;
System.out.println("Do you want to tip?");
tipConfirmation = Keyboard.next();
if (tipConfirmation.equalsIgnoreCase("yes")) {
System.out.print("What percentage would you like to tip? ");
C = Keyboard.nextInt();
double tiptotal = C * tip * subtotal;
double taxtotal = subtotal * salestax;
System.out.println("SubTotal $" + subtotal);
System.out.println("Tax " + salestax);
System.out.println("Tip $" + tiptotal);
System.out.println("-------------------------");
System.out.println(subtotal + tiptotal + taxtotal);
}
if (tipConfirmation.equalsIgnoreCase("no")) {
double tiptotal = C * tip * subtotal;
double taxtotal = subtotal * salestax;
System.out.println("SubTotal $" + subtotal);
System.out.println("Tax " + salestax);
System.out.println(subtotal + tiptotal + taxtotal);
}
} else
System.out.println("Invalid");
}
}
}
So one technique is to store the strings you want to use in a HashMap, then look them up to get the rest of the info that you need. For example:
static String[] foods = { "Good Burger", "Good Salad", "Kid's Meal", "Drink" };
static double[] costs = { 8.0, 7.0, 3.0, 0.75 };
HashMap<String, FoodItem> itemLookup = new HashMap<>();
{
for( int i = 0; i < foods.length; i++ ) {
itemLookup.put( foods[i], new FoodItem( foods[i], costs[i] ) );
}
}
That puts all your strings into a HashMap, plus a new object FoodItem which stores any additional relevant information you'd need to process the food item.
When the user enters a food name, just look it up in the HashMap.
FoodItem item = itemLookup.get( s.trim() );
if( item == null ) System.out.println("I couldn't find a "+ s );
Here I added a trim() to get rid of any white space, which would cause the string to be not found since HashMap only return exact matches.
That's the main idea. The following is a bit rough, but works (I tried it once) and gives you an idea how to put something together.
class FoodMenu {
class FoodItem {
public FoodItem( String name, double cost )
{
this.name = name;
this.cost = cost;
}
String name;
double cost;
#Override
public String toString()
{
return "FoodItem{" + "name=" + name + ", cost=" + cost + '}';
}
}
static String[] foods = { "Good Burger", "Good Salad", "Kid's Meal", "Drink" };
static double[] costs = { 8.0, 7.0, 3.0, 0.75 };
HashMap<String, FoodItem> itemLookup = new HashMap<>();
{
for( int i = 0; i < foods.length; i++ ) {
itemLookup.put( foods[i], new FoodItem( foods[i], costs[i] ) );
}
}
List<FoodItem> process( Reader input ) throws IOException {
BufferedReader bin = new BufferedReader( input );
ArrayList<FoodItem> order = new ArrayList<>();
for( String s; (s = bin.readLine()) != null && s.length() > 0; ) {
FoodItem item = itemLookup.get( s.trim() );
if( item == null ) System.out.println("I couldn't find a "+ s );
else order.add(item);
}
return order;
}
public static void main(String[] args) throws IOException {
System.out.println("Enter a food item name to order it.");
System.out.println("Items available: "+ Arrays.toString( foods ) );
System.out.println("Press enter on a blank line to finish");
List<FoodItem> order = new FoodMenu().process( new InputStreamReader( System.in ));
System.out.println("You ordered: "+order );
}
}
import java.util.Scanner;
public class CoffeeShop {
public static void main(String[] args) {
//Welcome message
String username;
System.out.println("Please enter your name");
Scanner keyboard = new Scanner(System.in);
username = keyboard.next();
System.out.println("Welcome to the Java Byte Code Coffee Shop," + username + "!");
//Menu
System.out.println("Here is our menu.");
System.out.println("1. Coffee $1.50");
System.out.println("2. Latte $3.50");
System.out.println("3. Cappuccino $3.25");
System.out.println("4. Expresso $2.00");
//Item selection
int item_Number;
System.out.println("Please enter an item number.");
Scanner item = new Scanner(System.in);
item_Number = item.nextInt();
if(item_Number == 1) {
item = 1.50;
}
if(item_Number == 2) {
item = 3.50;
}
if(item_Number == 3) {
item = 3.25;
}
if(item_Number == 4) {
item = 2.00;
}
//Item Quantity
int quantity;
System.out.println("Please enter the quantity.");
Scanner amount = new Scanner(System.in);
quantity = amount.nextInt();
double total = quantity * item;
System.out.println("Total before discount and tax is " + total);
//Discount and tax
double nuTotal;
if(total >= 10) {
nuTotal = total - (total * .1);
} else {
nuTotal = total;
}
System.out.println("Your total with discount is " + nuTotal);
double totalTax = nuTotal * .07;
System.out.println("Your total with tax is " + totalTax);
System.out.println("Thank you " + username + "! Please stop by again!");
}
}
Your assignment is to write a program called CoffeeShop (in the file CoffeeShop.java) that simulates a virtual coffee shop, allowing the user to select an item to purchase, along with the quantity of that item. After obtaining the item selection and desired quantity from the user, your program should calculate the cost, tax, discount, and final cost, then display these to the user.
The problem starts here:
Scanner item = new Scanner(System.in);
item_Number = item.nextInt();
if(item_Number == 1) {
item = 1.50;
}
if(item_Number == 2) {
item = 3.50;
}
if(item_Number == 3) {
item = 3.25;
}
if(item_Number == 4) {
item = 2.00;
}
item is a Scanner object but then you attempt to assign it a double value.
Then double total = quantity * item;. You multiply by a Scanner object.
Your error is in the following code.
First you declare:
Scanner item = new Scanner(System.in);
Then you try to set that scanner variable to be what I presume to be the price.
if(item_Number == 1) {
item = 1.50;
}
if(item_Number == 2) {
item = 3.50;
}
if(item_Number == 3) {
item = 3.25;
}
if(item_Number == 4) {
item = 2.00;
}
In order to fix this what you should do is set these numbers to a new variable, such as:
double price = 0;
price = ...; //not: item = ...;
Then you can calculate your total simply by:
double total = quantity * price;
Hope this helps! Just try to be very careful when setting variables :)
I believe your code should be similar to:
double price = 0;
if(item_Number == 1) {
price = 1.50;
}
if(item_Number == 2) {
price = 3.50;
}
if(item_Number == 3) {
price = 3.25;
}
if(item_Number == 4) {
price = 2.00;
}
double total = quantity * price;
This should help you a bit!
import java.text.DecimalFormat;
import java.util.Scanner;
public class JavaApplication2 {
public static void main(String[] args) {
//Welcome message
String username;
double item = 0.0;
Scanner keyboard = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("Please enter your name");
username = keyboard.next();
System.out.println("Welcome to the Java Byte Code Coffee Shop," + username + "!");
//Menu
System.out.println("Here is our menu.");
System.out.println("1. Coffee $1.50");
System.out.println("2. Latte $3.50");
System.out.println("3. Cappuccino $3.25");
System.out.println("4. Expresso $2.00");
//Item selection
int item_Number = 0;
System.out.println("Please enter an item number.");
item_Number = keyboard.nextInt();
if (item_Number == 1) {
item = 1.50;
}
if (item_Number == 2) {
item = 3.50;
}
if (item_Number == 3) {
item = 3.25;
}
if (item_Number == 4) {
item = 2.00;
}
//Item Quantity
int quantity = 0;
System.out.println("Please enter the quantity.");
quantity = keyboard.nextInt();
double total = quantity * item;
System.out.println("Total before discount and tax is $ " + df.format(total));
//Discount and tax
double nuTotal;
if (total >= 10) {
nuTotal = total - (total * 0.10);
} else {
nuTotal = total;
}
System.out.println("Your total with discount is $" + df.format(nuTotal));
double totalTax = nuTotal + (nuTotal * 0.07);
System.out.println("Your total with tax is: $" + df.format(totalTax));
System.out.println("Thank you " + username + "! Please stop by again!");
}
}
I advise you to follow name patterns for the Java programming language and its variables... you could see the documentation in here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
I also suggest you to initialize your variables in order to avoid Null values while validating.
Hope this helps! It's working already... but I'm not sure what are your expectations, good luck!
I have a project in mind however there are a few basics I need to master before I can proceed. Here's the issue I'm trying to call a function from main in java but I can't get it to compile. I have read the feedback and I went with using a switch to call each function. I always get "error can't find symbol". I've made a few changes here and there trying to get it to run. Once again I feel like I'm lacking something very fundamental and it's preventing me from getting this to work. Any ideas
import java.util.*;
import java.lang.*;
import java.io.*;
class Practice {
static void wagecalc() {
Scanner input = new Scanner(System.in);
System.out.println("Input pay per hour:");
int a = input.nextInt();
int b;
System.out.println("Input hours worked:");
b = input.nextInt();
int c;
System.out.println("Input days worked:");
c = input.nextInt();
int gross = a * b * c;
System.out.println("Your gross pay is:" + gross);
// Determining tax rate//
if (gross < 10000) {
int taxrate = gross * 10 / 100;
System.out.println("Your tax rate is 10%:/n");
int total = gross - taxrate;
System.out.println("Your net pay is:" + total + "/n");
}
else if (gross > 10000 || gross <= 30000) {
int taxrate = gross * 15 / 100;
System.out.println("Your tax rate is 15%:/n");
int total = gross - taxrate;
System.out.println("Your net pay is:" + total + "/n");
}
else if (gross >= 30000 || gross <= 70000) {
int taxrate = gross * 20 / 100;
System.out.println("Your tax rate is 20%:/n");
int total = gross - taxrate;
System.out.println("Your net pay is:" + total + "/n");
}
else if (gross > 70000) {
int taxrate = gross * 25 / 100;
System.out.println("Your tax rate is 25%:/n");
int total = gross - taxrate;
System.out.println("Your net pay is:" + total + "/n");
}
}
static void autocalc() {
Scanner input = new Scanner(System.in);
// Declaring the variables as an integer//
int auto;
int loan;
int interest;
int mnydwn;
int pymnt;
int year;
int month = 12;
int tap;
int term = year * month;
int spec;
System.out.println("Please enter the following information for your car loan:/n");
System.out.println("Please enter the amount of the vehicle you wish to purchase:/n");
auto = input.nextInt();
System.out.println("Please enter the amount of money you wish to put down:/n");
mnydwn = input.nextInt();
System.out.println("Please enter the interest rate:/n");
interest = input.nextInt();
System.out.println("Please enter the term of the loan (years):/n");
year = input.nextInt();
System.out.println("Processing......../n");
System.out.println("Processing............");
// Calculations//
loan = auto - mnydwn;
int intamt = loan * interest;
tap = loan + intamt;
pymnt = tap / term;
// Display//
System.out.println("Process...Complete./n");
System.out.println("Car amount:" + auto);
System.out.println("Loan recieved:" + loan);
System.out.println("Interest rate:" + interest);
// if statement for proper output of year//
if (year == 1) {
System.out.println("Your monthly payments will be" + pymnt + "for a" + year + "year" + term + "months.");
} else if (year > 1) {
System.out.println("Your monthly payments will be" + pymnt + "for" + year + "years" + term + "months.");
}
System.out.println("Total amount paid at the end of the term" + tap);
}
public static void main(String[] args) throws java.lang.Exception {
// User input//
Scanner input = new Scanner(System.in);
int count = 0; // Count for the while loop//
// Instructions on how to begin interface//
System.out.println("Hi!/n");
System.out.println("...Thanks for using D Anomaly's Finance calculator!!/n");
System.out.println("Please choose one of the following:/n");
System.out.println(" 1. Wages:/n");
System.out.println(" 2. Auto Loan:/n");
// System.out.println(" 3. Home Loan:/n");//
System.out.println("Choose 1-3");
int calc = input.nextInt();
switch (calc) {
case 1:
wagecalc();
break;
case 2:
autolcalc();
break;
case 3: // homecalc();//
break;
if (calc >= 4) {
System.out.println(" Invalid entry!!!/n");
System.out.println("Please try again:");
break;
}
}
}
}
There are a few problems here, including the following:
1.
public void wageinformation(int gross) needs to be declared static if you want to call it from main()
2.
You are calculating int gross = a * b * c right after you have received it as a parameter.
3.
You have (or had in the initial version of this post) several extra braces.
4.
The deduction and total variables are never declared within the wageinformation() method.
I would strongly suggest working through some online Java tutorials if you are looking to improve your skills.