I want to print what I've ordered in the starters method with the quantity when printing the bill. Any suggestions as to how I will do it? I have only written an instance of my program since it the entire problem is very large.
Thanks in advance.
static void Bill()
{
System.out.println("\f");
System.out.println("*********************************************************");
System.out.println("*********************************************************");
System.out.println("**************************BILL***************************");
System.out.println(ob);
System.out.println("Your phone number - "+j);
int Z = (int)(Math.random()*10000000);
System.out.println("Bill number is "+Z);
System.out.println("The total bill amount is Rs."+sum);
System.out.println();
System.out.println("Hope you enjoyed. Visit us again soon!");
Food=0;
}
static void Starters()
{
System.out.println("You have selected Starters");
System.out.println();
System.out.println("1. Spring Rolls - Rs 350");
System.out.println("2. Onion Rings - Rs 350");
System.out.println("3. Fried Raviolli - Rs 400");
System.out.println("4. Gorgonzola - Rs 400");
System.out.println("5. Fresh Ricotta Crostini - Rs 475");
System.out.println("6. Potato Fritters - Rs 500");
System.out.println();
System.out.println("Enter your desired option");
starterOption=sc.nextInt();
System.out.println("Enter quantity");
quantity=sc.nextInt();
switch(starterOption)
{
case 1:
s1 = quantity * 350;
break;
case 2:
s2 = quantity * 350;
break;
case 3:
s3 = quantity * 400;
break;
case 4:
s4 = quantity * 400;
break;
case 5:
s5 = quantity * 475;
break;
case 6:
s6 = quantity * 500;
break;
default:
System.out.println("You haven't ordered anything");
break;
}
System.out.println("Do you want to order anything else? Y/N");
A = sc1.next();
if(A.equalsIgnoreCase("Y"))
{
System.out.println("Do you want to order from the same section? Y/N ");
F=sc.next();
if(F.equalsIgnoreCase("Y"))
{
sum=s1+s2+s3+s4+s5+s6;
Starters();
}
else
{
sum=s1+s2+s3+s4+s5+s6;
Food_Items();
}
}
else
{
sum=s1+s2+s3+s4+s5+s6;
Bill();
}
}
As mentioned above: this is a very long code for a really simple problem.
When you want to print what was ordered, then you have to save it in a variable, e.g. an array. Or as suggested in a Collection e.g. a List. You can expand your code in the same manner you did it. But it's strongly recommended that you refine your code.
I suggest using a HashMap, read the example in the tutorial in this link
A possible solution to your issue could be :-
Declare variable in the class, preferable 'private'
private static HashMap<String, Integer> Starters = new HashMap<String, Integer>();
private static HashMap<String, Integer> Orders = new HashMap<String, Integer>();
Initialize these using some Init Function or the Constructor of the class with all the possible values for Startres
Starters.put("Spring Rolls", 350);
Starters.put("Onion Rings", 400);
in the Starters() Function you could use (stripped down sample)
System.out.println("You have selected Starters");
System.out.println();
int i = 1;
String[] mystarters = Starters.keySet().toArray(new String[Starters.keySet().size()]);
for (String starter : mystarters) {
System.out.println(i++ + ". " + starter + " : Rs. " + Starters.get(starter));
}
System.out.println("Enter your desired option");
//get option
System.out.println("Enter quantity");
//get quantity
// I am using s. as a prefix for starters, for Main course you could use m. or mc. or something
Orders.put("s." + mystarters[option - 1], quantity);
Of course, you could get the Quantity if this Starter already exists in the order and add to the existing quantity, or ask if it needs to be overwritten.
// example
if(Orders.containsKey("s." + mystarters[option - 1]))
Orders.put(("s." + mystarters[option - 1]), Orders.get("s." + mystarters[option - 1])+quantity);
else
Orders.put("s." + mystarters[option - 1], quantity);
In Bill , you could use the following :-
int sum = 0;
for (String orderItem : Orders.keySet()) {
int price = 0;
int quant = Orders.get(orderItem);
if (orderItem.startsWith("s.")) {
orderItem = orderItem.substring(2);
price = Starters.get(orderItem);
System.out.println(orderItem + " x " + quant + " = Rs. " + price * quant);
}
sum += price * quant;
}
System.out.println("Total Price : Rs." + sum);
There are several improvement you could do to your code. You have to store what you have already order, if you want to show all the elements on the bill. Each time you order, you can add the element to a List
You need to store objects in the list, so you could create some objects for your dishes. Enums seems to be appropiate to your application, this could be some example for the starters:
enum Starters {
SPRING_ROLLS("Spring Rolls", "Rs 350", 5),
FRIED_RAVIOLLI("Fried Raviolli", "Rs 400", 9),
... // All other starters...
String name;
String code;
int price;
public Starters(String name, String code, String price) {
this.name = name;
this.code = code;
this.price = price;
}
public String getName() {
return name;
}
public String getCode(){
return code;
}
public int getPrice(){
return price;
}
}
Then you display your menus like this:
for (Starters starter : Starters.values()) {
System.out.println(starter.getName() + " " starter.getCode()); // Just an example, modify to fit your format
}
You are going to have different types of enums and you want to add objects of the same type to the list. You can use an interface for this and make all enums to implement the interface:
public interface Orderable {
public String getName();
public String getCode();
public String getPrice();
}
You can initialize the list like this:
List<Orderable> orders = new ArrayList<>();
And add elements to the list like this (The enums need to implement the Orderable interface):
orders.add(Starters.SPRING_ROLLS);
order.add(Desserts.CHEESE_CAKE);
...
When you want to display the bill, you can iterate over the list and display the orders:
int totalPrice = 0;
for (Orderable order : orders) {
System.out.println(order.getName() + " - " order.getPrice());
totalPrice += order.getPrice();
}
System.out.println("Total price: ");
Related
I am a complete beginner in programming and I'm working on a program for my mother that tracks her employee's monetary intake through a "horse race", with each employee having a horse and the program tracking their input to a UI made to look like a racetrack. After the help from my last inquiry, I've greatly simplified my mess of code but I am now faced with a new problem in that, after sorting the values largest to smallest, I have no way of associating the sorted values with the correct horse. I understand this explanation is confusing so I hope my code will do most of the talking for me here.
I honestly have no idea where to start with this. As I said in my last inquiry, I'm a complete beginner and severely lack the terminology or knowledge to find an answer here.
public class HorseRace {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String horse1 = "#5 Gitty-Up";
String horse2 = "#7 Lady Simmons";
String horse3 = "#6 Burning Peanutbutter";
String horse4 = "#10 White Lightning";
String horse5 = "#3 Bella";
String horse6 = "#1 Meg The Stallion";
float h1val;
float h2val;
float h3val;
float h4val;
float h5val;
float h6val;
System.out.println("Input amount for " + horse1 + ":");
h1val = sc.nextFloat();
System.out.println("Input amount for " + horse2 + ":");
h2val = sc.nextFloat();
System.out.println("Input amount for " + horse3 + ":");
h3val = sc.nextFloat();
System.out.println("Input amount for " + horse4 + ":");
h4val = sc.nextFloat();
System.out.println("Input amount for " + horse5 + ":");
h5val = sc.nextFloat();
System.out.println("Input amount for " + horse6 + ":");
h6val = sc.nextFloat();
Float[] values = new Float[]{h1val, h2val, h3val, h4val, h5val, h6val};
Arrays.sort(values, Collections.reverseOrder());
//currently displays horses with the wrong number. Need a way to tie the horse name strings to their respective float elements
System.out.println("The current race progress is :");
System.out.println(horse1 + " with $" + values[0]);
System.out.println(horse2 + " with $" + values[1]);
System.out.println(horse3 + " with $" + values[2]);
System.out.println(horse4 + " with $" + values[3]);
System.out.println(horse5 + " with $" + values[4]);
System.out.println(horse6 + " with $" + values[5]);
}
}
my desired result is printing the correct horse with the correct value. For example, if I put that #5 brought in $11 and #7 brought in $14, the program would print that #7 is in the lead with $14 and #5 is in second place with $11.
Currently, the program always prints #5 as being in the lead with the highest value, #7 being in second with the second highest, etc.
I understand this is because I am hard calling the horse1-horse6 values meaning they don't change, but these are acting more as placeholders while I figure out how to associate the right horse with the right value
This is where you should create a Horse class and store the data as instances of Horse.
class Horse {
private String name;
private float value;
public String getName() { return name; }
public float getValue() { return value; }
public void setName(String name) { this.name = name; }
public void setValue(float value) { this.value = value; }
}
And then in your main method:
Horse[] horses = new Horse[6] {
new Horse(), new Horse(), new Horse(), new Horse(), new Horse(), new Horse()
};
horses[0].setName("#5 Gitty-Up");
horses[1].setName("#7 Lady Simmons");
horses[2].setName("#6 Burning Peanutbutter");
// and so on...
// you should use a for loop here instead of writing similar lines over and over again!
for (int i = 0 ; i < 6 ; i++) {
System.out.println("Input amount for " + horses[i].getName() + ":");
horses[i].setValue(sc.nextFloat());
}
Arrays.sort(horses, Comparator.comparingDouble(Horse::getValue).reversed());
System.out.println("The current race progress is :");
for (int i = 0 ; i < 6 ; i++) {
System.out.println(horses[i].getName() + " with $" + horses[i].getValue());
}
By using a class, you are essentially grouping data that belongs together, together. On the line Arrays.sort(horses, Comparator.comparingDouble(Horse::getValue).reversed());, I am sorting the whole array of horses together, by their values.
If the concepts of classes and objects are new to you, that just means it's time to learn about some new concepts. Classes and objects are very important.
Step 1, create a Horse class. It should have two fields, amount and name. It should implement Comparable because you want to sort it. And looking at your desired output, I would override toString().
class Horse implements Comparable<Horse> {
private String name;
private float amount;
public Horse(String name, float amount) {
this.name = name;
this.amount = amount;
}
#Override
public String toString() {
return String.format("%s with $%.2f", name, amount);
}
#Override
public int compareTo(Horse o) {
return Comparator.comparing((Horse h) -> h.amount)
.thenComparing((Horse h) -> h.name).compare(this, o);
}
}
Step 2, create an array of horseNames and iterate that populating an array of Horses (with amounts). Then sort it, and I would prefer Comparator.reverseOrder() to Collection.reverseOrder() when sorting an array.
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String[] horseNames = { "#5 Gitty-Up", "#7 Lady Simmons",
"#6 Burning Peanutbutter", "#10 White Lightning",
"#3 Bella", "#1 Meg The Stallion" };
Horse[] horses = new Horse[horseNames.length];
for (int i = 0; i < horseNames.length; i++) {
System.out.printf("Input amount for %s:%n", horseNames[i]);
float amt = sc.nextFloat();
horses[i] = new Horse(horseNames[i], amt);
}
Arrays.sort(horses, Comparator.reverseOrder());
System.out.println("The current race progress is :");
for (int i = 0; i < horses.length; i++) {
System.out.println(horses[i]);
}
}
I am creating a small game-type program,
Firstly I'm asking the user to give his name,
Secondly, I'm asking the user to choose one of the spaceships,
Thirdly, I want the user to add 2 modification, to improve the stats...
Here is the problem, I want to change some values of the spaceship.
The problem is that I don't know how to determine the chosen spaceship and how to change its values. Example: The Heavy-type Armour is 90 right now if I add the Advanced Hull Armour modification, i want it to increase to 100
public class Game {
static void playerName() {
System.out.println("What's your name?:");
String name = Keyboard.readString();
System.out.println("Okay,"+name+" it is!\n");
}
static class StarShip {
String name;
String armour;
String attack;
String mobility;
}
public static void main (String args[]) {
System.out.println("Hello Rookie! \n");
playerName();
System.out.println("Let's pick your first ship!\n");
System.out.println("Choose one of these:");
//insert ships here:
StarShip ship1 = new StarShip();
ship1.name = "Heavy-type";
ship1.armour = "Armour=90";
ship1.attack = "Firepower=50";
ship1.mobility = "Mobility=40";
StarShip ship2 = new StarShip();
ship2.name = "Medium-type";
ship2.armour = "Armour=60";
ship2.attack = "Firepower=60";
ship2.mobility = "Mobility=60";
StarShip ship3 = new StarShip();
ship3.name = "Light-type";
ship3.armour = "Armour=20";
ship3.attack = "Firepower=60";
ship3.mobility = "Mobility=90";
System.out.println("1 -"+ship1.name+"- "+ship1.armour+" "+ship1.attack+" "+ship1.mobility);
System.out.println("2 -"+ship2.name+"- "+ship2.armour+" "+ship2.attack+" "+ship2.mobility);
System.out.println("3 -"+ship3.name+"- "+ship3.armour+" "+ship3.attack+" "+ship3.mobility);
int chosen = Keyboard.readInt();
switch (chosen) {
case 1:
System.out.println("Heavy-type! Excellent choice! Great armour and guns! \n");
break;
case 2:
System.out.println("Medium-type! An all-rounder, a mix of everything! \n");
break;
case 3:
System.out.println("Light-type! Fast and mobile, but has little armour! \n");
break;
}
System.out.println("Lets pimp out your ship! \n");
String advancedHull = "1 - Advanced Hull Armour - Armour +10";
String betterAmmo = "2 - Better Ammo \t - Firepower +10";
String booster = "3 - Booster \t\t - Mobility +10";
System.out.println(advancedHull+"\n"+betterAmmo+"\n"+booster);
}
}
Currently you the fields of the StarShip are all Strings, when you add two strings they are concatenated, eg "abc"+"def" = "abcdef" regardless of what they say. You want to use ints these are "java numbers" and add as you would expect eg 10 + 20 = 30
class StarShip {
String name;
int armour;
int attack;
int mobility;
}
...
StarShip ship1 = new StarShip();
ship1.name = "Heavy-type";
ship1.armour = 90;
ship1.attack = 50;
ship1.mobility = 40;
...
When the user selects the ship we want to save this chose into a variable, like so:
Starship chosenShip; // must be declared outside the switch statement
switch (shipChoice ) {
case 1:
System.out.println("Heavy-type! Excellent choice! Great armour and guns! \n");
chosenShip = ship1;
Break;
...
Assuming advancedHull is selected and you include logic similar to how ships are selected
if (modificationChoice = 1){
chosenShip.armour = chosenShip.armour + 10;
} ...
You may want to declare a toSting() methods in StarShip like so
#Override
public String toString() {
return name +" Armour=" + armour +", Firepower=" + attack +", Mobility=" + mobility;
}
This way you can call System.out.println(ship1.toString()) to print the ship info.
Example:
System.out.println(ship1.toString());
// outputs: Heavy-type Armour=90, Firepower=50, Mobility=40
ship1.armour += 10; // java shorthand for `ship1.armour + ship1.armour + 10`
System.out.println(ship1.toString());
// outputs: Heavy-type Armour=100, Firepower=50, Mobility=40
The following code asks the user to input the description, price and quantity of item he consumed.
There is a while loop to ask if he wants to input more items! If he does, the program ask to insert another description, price and quantity of the other items, and so on.
If he doesn't want to input more items, the output is all the items he added to the array, and the total of the bill.
Problem is: the first time the while runs, it works, but on the second time if the user answer with "y", it returns an error, as if he jumped from the description right to the price of the second item. If the user type the description, then it gets an input mismatch exception.
Main Class:
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Gastos> billArr = new ArrayList<>();
Scanner input = new Scanner(System.in);
int qntItems = 0 , counter = 0;
String ans;
Gastos bill = new Gastos();
while (qntItems == 0) {
System.out.print("Want to input another item? Y/N: ");
ans = input.nextLine();
switch (ans){
case "y":
qntItems = 0;
bill.setDescription();
bill.setPrice();
bill.setQuantity();
bill.getTotal();
billArr.add(bill);
counter = counter + 1;
break;
case "n": qntItems = 1;
break;
default: System.out.print("Invalid!");
System.out.println();
break;
}
input.close();
}
for (int i = 0; i < billArr.size();i++){
System.out.print(bill.getDescription() + ", " + bill.getPrice() + ", " + bill.getQuantity() + ", " + "the total is: " + bill.getTotal());
}
}
}
and the Gastos class:
package com.company;
import java.util.Scanner;
public class Gastos {
private String description;
private double price, quantity, total;
private Scanner input = new Scanner(System.in);
public void setDescription(){
System.out.print("Insert the item name: ");
description = input.nextLine();
}
public void setPrice(){
System.out.print("insert the item price: ");
price = input.nextDouble();
}
public void setQuantity(){
System.out.print("Insert the quantity: ");
quantity = input.nextDouble();
}
public String getDescription(){
return description;
}
public double getPrice() {
return price;
}
public double getQuantity() {
return quantity;
}
public double getTotal(){
total = price * quantity;
return total;
}
}
How can I handle this error?
You have a bug in your 2nd loop.
It should be:
System.out.print(billArr.get(i).getDescription().....
or simply put:
for(Gastos b : billArr){
System.out.print(b.getDescription())
}
Update 1: Another error is you close the Scanner at the end of the first loop. Move input.close(); outside the loop or inside case "n".
Update 2: You have another problem, you need to reinitialize Gastos every time you enter new details about it. So you need to do Gastos bill = new Gastos(); right after case "y": and remove it from where you initialize it before the while loop. Your main should look like this:
public static void main(String[] args) {
ArrayList<Gastos> billArr = new ArrayList<>();
Scanner input = new Scanner(System.in);
int qntItems = 0 , counter = 0;
String ans;
while (qntItems == 0) {
System.out.print("Want to input another item? Y/N: ");
ans = input.nextLine();
switch (ans){
case "y":
Gastos bill = new Gastos();
qntItems = 0;
bill.setDescription();
bill.setPrice();
bill.setQuantity();
bill.getTotal();
billArr.add(bill);
counter = counter + 1;
break;
case "n": qntItems = 1;
input.close();
break;
default: System.out.print("Invalid!");
System.out.println();
break;
}
}
for (Gastos bill : billArr){
System.out.print(bill.getDescription() + ", " + bill.getPrice() + ", " + bill.getQuantity() + ", " + "the total is: " + bill.getTotal());
}
}
I think you need to spend sometime debugging and understanding how java's objects work. These are basic errors which should be easily caught.
the question is :
A fruit shop sells several types of fruits each day. Write a program that reads from user several lines of input.Each line includes a fruit's name,price per kilogram (as an integer), number of kilograms sold (as an integer).
the program should calculate and print the earned money of all fruits sold and fruit that achieved largest profit.
hint: -you could assume that user will insert valid data -user could stop the program via entering the word "stop" as a fruit's name.
Sample input and out put:
in each line, insert a fruit's name, price per kilogram, number of kilograms sold. To halt the program,insert "stop" as a fruit's name
banana 2 11
mango 3 8
peach 4 5
stop
the earned money of all fruits sold: 66
fruit that achieved the largest profit: mango
what i wrote now:
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String fruitname= " ";
String maxfruit = " ";
int price = 0,number=0;
int sum=0;
int max=0;
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
while (!fruitname.equals("stop"))
{
fruitname = input.next();
price = input.nextInt();
number = input.nextInt();
}
if (fruitname.equals("stop"))
{
sum = sum+(price*number);
}
if (max<(price*number))
{
max = price*number;
maxfruit = fruitname;
}
System.out.println("the earned money of all fruits is " + sum);
System.out.println("fruit that achieved the largest profit is "+ maxfruit);
}
}
the program is not reading what i submit to it, don't know why and not giving me the sum and the max fruit.. what is the problem of what i wrote?
As you can see your reads happen in the while loop:
while (!fruitname.equals("stop"))
{
fruitname = input.next();
price = input.nextInt();
number = input.nextInt();
}
Every time it loops - it overrides the values. Finally when you read stop and exit the loop - your fruitname is stop. So you need to fix your logic on how you would want to read in the input
Working variant:
public class FruitTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
String text = input.nextLine();
String[] words = text.split(" ");
List<Fruit> fruits = parseInput(words);
int sum = getSum(fruits);
String popular = getPopularFruitName(fruits);
System.out.println("Got fruits: " + fruits.toString());
System.out.println("the earned money of all fruits is " + sum);
System.out.println("fruit that achieved the largest profit is " + popular);
}
private static String getPopularFruitName(List<Fruit> fruits) {
int max = 0;
String name = null;
for (Fruit fruit : fruits) {
int checkVal = fruit.getPrice() * fruit.getAmount();
if(checkVal > max) {
max = checkVal;
name = fruit.getName();
}
}
return name;
}
private static int getSum(List<Fruit> fruits) {
int result = 0;
for (Fruit fruit : fruits) {
result += fruit.getPrice() * fruit.getAmount();
}
return result;
}
private static List<Fruit> parseInput(String[] words) {
List<Fruit> result = new ArrayList<Fruit>();
int element = 1;
final int name = 1;
final int price = 2;
final int amount = 3;
Fruit fruit = null;
for (String word : words) {
if (word.equals("stop") || word.isEmpty()) {
break;
}
if(element > amount)
element = name;
switch (element) {
case name:
fruit = new Fruit(word);
result.add(fruit);
break;
case price:
if (fruit != null) {
fruit.setPrice(Integer.valueOf(word));
}
break;
case amount:
if(fruit != null) {
fruit.setAmount(Integer.valueOf(word));
}
break;
}
element++;
}
return result;
}
static class Fruit {
String name;
int price = 0;
int amount = 0;
Fruit(String name) {
this.name = name;
}
String getName() {
return name;
}
int getPrice() {
return price;
}
void setPrice(int price) {
this.price = price;
}
int getAmount() {
return amount;
}
void setAmount(int amount) {
this.amount = amount;
}
#Override
public String toString() {
return name + ". $" + price +
", amount=" + amount;
}
}
}
Comments to code - it's proper way to parse all the inputted string and parse it to an object that stores all the data - name, price and amount. Store all parsed objects into array or a list and then calculate max and popular fruit while looping your parsed fruit array
I found some mistake. The most important was in the while condition. Check this out.
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String fruitname = null;
String maxfruit = null;
int fruitSum = 0;
int totalSum = 0;
int max = 0;
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
while(!(fruitname = input.next()).equals("stop")){
fruitSum = input.nextInt() * input.nextInt();
totalSum += fruitSum;
if(fruitSum > max){
maxfruit = fruitname;
max = fruitSum;
}
}
System.out.println("the earned money of all fruits is " + totalSum);
System.out.println("fruit that achieved the largest profit is "+ maxfruit);
}
}
Oh it is reading it.
the problem is that it doesn't do what you want it to do.
the problems with the code I can see are this:
you are not storing the fruits quantities or prices anywhere, you need to store the values
in an array or something (maxFruit,MaxValue) to compare them later.
when you are reading the fruit values and a "stop" string is input the next step in your code is to wait for the price so it won't get out of the loop even if you input "stop", you need to restructure your scanner loop.
And if it is a beginner class it may be ok, but the code you are writing is not object oriented don't write the logic in the main.
You may want to learn to debug it is a very useful tool when you are learning to code, if you run this program in debug mode , you could see that the values are getting input and everything that is happening, Netbeans and Eclipse have very good debuggers and it would be worth to expend half an hour learning the basics of debugging It certainly helped me a lot when I was starting.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class FruitSells {
public static void main(String... args) {
BufferedReader bufer = new BufferedReader(new InputStreamReader(System.in));
try {
String str;
String[] inarr;
int sumMoney = 0;
do {
str = (String) bufer.readLine();
inarr = str.split(" ");
for(int i = 1; i < inarr.length; i += 3) {
sumMoney += Integer.parseInt(inarr[i]) * Integer.parseInt(inarr[i + 1]);
}
System.out.println(sumMoney);
sumMoney = 0;
} while (!str.equals("stop"));
} catch(IOException ex) {
System.out.println("Problems with bufer.readLine()");
}
}
}
something like this you can modernize it.sorry for eng i can not speak))and write correctly of course))
I'm trying to create a program that allows the user to say, input (orange/apple/banana/etc), then the quantity they want to purchase, and the program will calculate the total. However, after trying Strings (Can't multiply them) and a few other options, I'm stuck. I've intensively browsed this forum along with countless guides, to no avail.
The IF statement I inserted was simply a last ditch random attempt to make it work, of course, it crashed and burned. This is all basic stuff I'm sure, but I'm quite new to this.
I would also like to display a list to choose from, perhaps something like
Oranges: Qnty: (Box here)
Apples: Qnty: (Box here)
Bananas: Qnty: (Box here)
Etc
But I'd really settle for help as how to allow the user to input a word, orange, and it is assigned the value I have preset so I can multiply it by the quantity.
All help is appreciated, criticism too of course, to you know, a reasonable extent...
Here's my code.
/* Name 1, x0000
* Name 2, x0001
* Name 3, x0003
*/
import java.util.Scanner;
public class SD_CA_W3_TEST1
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
double nameOfItem1, nameOfItem2, nameofItem3;
double quantityItem1, quantityItem2, quantityItem3;
final double apple = 0.30;
final double orange = 0.45;
final double strawberry = 2.30;
final double potato = 3.25;
final double turnip = 0.70;
final double carrot = 1.25;
double totalCost;
String strNameOfItem1;
System.out.println(" \t \t What would you like to buy today?");
System.out.print("Please choose from our fine selection of: oranges, strawberries, potatoes, turnips, and carrots. \n" );
System.out.print("Enter name of product ");
nameOfItem1 = in.nextDouble();
nameOfItem1 = If = nameOfItem1 (apple, orange, strawberry, potato, turnip, carrot);
System.out.print("Please enter a quantity to purchase");
quantityItem1 = in.nextDouble();
totalCost = quantityItem1 * strNameOfItem1;
System.out.print("The total cost of your purchase is: " +totalCost );
}
}
I would use a HashMap. Here's a good tutorial:
http://www.tutorialspoint.com/java/util/hashmap_get.htm
HashMap food = new HashMap();
food.put("Apple", 0.30);
food.put("Orange", 0.45);
...
then use
food.get("Apple");
to give you the price.
the grand total would be something like:
double quantity = 4.0;
double total = food.get("apple") * quantity;
Try using enums,
class Test{
public enum Fruits{
apple(0.30), orange(0.45), strawberry(2.30), potato(3.25);
private final double value;
Fruits(double value1){
value = value1;
}
public double getValue(){
return value;
}
}
public static void main(String[] args) {
int quantity = 0;
// Read your value here and assign it to quantity
System.out.println(Fruits.apple.getValue()*quantity);
}
}
Enum seems to be a good choice here. It would help you map your item names to the price easily instead of creating several double variables.
private enum Items {
APPLE(0.30), ORANGE(0.45), STRAWBERRY(2.30),
POTATO(3.25), TURNIP(0.70), CARROT(1.25);
double price;
Items(double price) {
this.price = price;
}
double getPrice() {
return price;
}
}
Use Scanner#next() to read in String and use Enum.valueOf() to validate and convert user input into one of your Items.
Scanner in = new Scanner(System.in);
System.out.println("What would you like to buy today?");
System.out.println("Please choose from our fine selection of: " +
"Orange, Strawberry, Potato, Turnip, and Carrot.");
System.out.print("Enter name of product: ");
String nameOfItem = in.next();
Items item;
try {
// Validate Item
item = Items.valueOf(nameOfItem.toUpperCase());
} catch (Exception e) {
System.err.println("No such item exists in catalog. Exiting..");
return;
}
System.out.print("Please enter a quantity to purchase: ");
int quantity;
try {
quantity = in.nextInt();
if (!(quantity > 0)) { // Validate quantity
throw new Exception();
}
} catch (Exception e) {
System.err.println("Invalid quantity specified. Exiting..");
return;
}
double totalCost = quantity * item.getPrice();
System.out.printf("The total cost of your purchase is: %.2f", totalCost);
Output :
What would you like to buy today?
Please choose from our fine selection of: Orange, Strawberry, Potato, Turnip, and Carrot.
Enter name of product: Strawberry
Please enter a quantity to purchase:3
The total cost of your purchase is: 6.90