Last line doesn't print? - java

When I run the program everything works fine until I get to the last line where I want to to multiply the price of gas depending on the type, however that part does not print out.
{
public static void main(String[] args)
{
double R = 2.19;
double M = 2.49;
double P = 2.71;
System.out.println("What type of gas?");
System.out.println("(R)egular: 2.19");
System.out.println("(M)idgrade: 2.49");
System.out.println("(P)remium: 2.71");
String gastype;
gastype = S.nextLine();
System.out.println("How many gallons?");
double gallons;
gallons = S.nextDouble();
if ((R * gallons) == 0)
{
System.out.println("You owe: " +R * gallons+ "");
}
if ((M * gallons) == 0)
{
System.out.println("You owe: " +M * gallons+ "");
}
if ((P * gallons) == 0)
{
System.out.println("You owe: " +P * gallons+ "");
}
}
}

For your code snippet to print total price, it should be something like:
double total;
// check for user input of "gas type"
// calculate total = gas type * gallons
if (gasType.equals("R")) {
total = R * gallons;
} else if (gasType.equals("M")) {
total = M * gallons;
} else if (gasType.equals("P")) {
total = P * gallons;
} else {
System.out.println("Invalid type of gas");
return;
}
System.out.println("You owe: %f", total);

Use this
public static void main(String[] args) {
double R = 2.19;
double M = 2.49;
double P = 2.71;
System.out.println("What type of gas?");
System.out.println("(R)egular: 2.19");
System.out.println("(M)idgrade: 2.49");
System.out.println("(P)remium: 2.71");
String gastype;
gastype = S.nextLine();
System.out.println("How many gallons?");
double gallons;
gallons = S.nextDouble();
if ((gasType == 'R') {
System.out.println("You owe: " +R * gallons+ "");
}
else if (gasType == 'M') {
System.out.println("You owe: " +M * gallons+ "");
}
else if (gasType == 'P') {
System.out.println("You owe: " +P * gallons+ "");
}
else {
System.out.println("Wrong GasType")
}
}

Your if statements will only execute if gallons = 0. Not only that, but you aren’t checking to see which gas the customer wanted. You’re essentially ignoring the gastype altogether for your final answer.
Try this if statement as an example
if (gasType.equals(“Regular”) {
//Stuff you want to print
}

Related

how to add try and catch for this Java Program?

and i just created a program for fare with discount. but I dont know where to put the try and catch.
this is the program without try and catch
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String passengerType;
double distance;
double minimumFare = 20;
double fare1, finalFare;
System.out.println("Enter the type of Passenger (Ordinary/Student/Senior): ");
passengerType = input.nextLine();
System.out.println("Enter the Distance: ");
distance = input.nextDouble();
// Condition for "Ordinary Passenger"
if (passengerType.equalsIgnoreCase("Ordinary"))
{
if (distance <= 10)
{
System.out.println("Your Fare is: "+minimumFare);
}
else if (distance > 10)
{
fare1 = (distance - 10) * 2.50;
finalFare = fare1 + minimumFare;
System.out.println("Your Fare is: "+finalFare);
}
}
// Condition for "Student Passenger"
else if (passengerType.equalsIgnoreCase("Student"))
{
if (distance <= 10)
{
finalFare = 20 - (20 * 0.20);
System.out.println("Your Fare is: "+ finalFare);
}
else if (distance > 10)
{
fare1 = ((distance - 10) * 2.50);
finalFare = fare1 + 20 - ((fare1 + 20) * 0.20);
System.out.println("Your Fare is: "+finalFare);
}
}
// Condition for "Senior Passenger"
else if (passengerType.equalsIgnoreCase("Senior"))
{
if (distance <= 10)
{
finalFare = 20 - (20 * 0.30);
System.out.println("Your Fare is: "+ finalFare);
}
else if (distance > 10)
{
fare1 = ((distance - 10) * 2.50);
finalFare = fare1 + 20 - ((fare1 + 20) * 0.30);
System.out.println("Your Fare is: "+ finalFare);
}
}
}
}
the output of the program must be these.(when error input)
thank you so much in advance, its my first time in java language. please don't vote negative ^_^
I'm also new at this, but if you were to run the programme, and try to put in a different input than suggested. For example putting string where you need an int or putting an int where you need string, when you run the programme the compiler will show you the exceptions which you need to catch.
I've altered the start of the programme, just to show you how i'd do it, i'm also not the best but hopefully this puts you on the right track
Scanner input = new Scanner(System.in);
String passengerType = null;
double distance = 0;
double minimumFare = 20;
double fare1, finalFare;
try {
System.out.println("Enter the type of Passenger (Ordinary/Student/Senior): ");
passengerType = input.nextLine();
System.out.println("Enter the Distance: ");
distance = input.nextDouble();
} catch (InputMismatchException e){
System.out.println("Please enter strings for passenger and numbers for distance " + e);
}
also check out the link
When should an IllegalArgumentException be thrown?
Your code never throws any Exception. try and catch blocks are used to catch Exceptions that may be thrown when calling methods that throw them (you can see it on method declaration). If you want to output that an argument is invalid, add an else statement after your conditions, and throw an IllegalArgumentException:
else {
throw new IllegalArgumentException("You did something wrong");
}
Or if you want a "cleaner" error, output it to System.err, so that the user doesn't need to see the stack trace:
else {
System.err.println("Invalid Passenger Type");
}
The same goes to checking if distance is a String, like the other answer showed.
In this case, you are making use of a Scanner which needs to be closed after use, so it is best to go with a try-with-resources statement which will take care of automatically closing the Scanner when it is done.
Also, in order to ensure valid input is gotten, I have included an input checker to keep reading until a valid string is entered for Passenger and a Distance >= 0 is entered.
In the case of Distance, using the input.nextDouble() ensures the input is a valid number and will throw an InputMismatchException if it is not a valid number. Consider reading the input as a String and parse it to Double, that way you have more control over what happens and can demand a new input without the program being terminated. The way it is currently, the program will get terminated as there is no way to read a new input after displaying the error message.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
String passengerType;
double distance;
double minimumFare = 20;
double fare1, finalFare;
try(Scanner input = new Scanner(System.in);){
System.out.println("Enter the type of Passenger (Ordinary/Student/Senior): ");
passengerType = input.nextLine();
while(passengerType == null || passengerType.trim().equals("") || (!passengerType.equals("Ordinary") && !passengerType.equals("Student") && !passengerType.equals("Senior"))){
System.out.println("Valid Passengers are Ordinary/Student/Senior: ");
passengerType = input.nextLine();
}
System.out.println("Enter the Distance: ");
distance = input.nextDouble();
while(distance < 0){
System.out.println("Distance must be greater than or equal to 0: ");
distance = input.nextDouble();
}
System.out.println("Input read: " + passengerType + ", " + distance);
} catch (InputMismatchException e){
System.out.println("Distance must be a number");
return;
} catch (Exception e){
e.printStackTrace();
return;
}
// Condition for "Ordinary Passenger"
if (passengerType.equalsIgnoreCase("Ordinary"))
{
if (distance <= 10)
{
System.out.println("Your Fare is: "+minimumFare);
}
else if (distance > 10)
{
fare1 = (distance - 10) * 2.50;
finalFare = fare1 + minimumFare;
System.out.println("Your Fare is: "+finalFare);
}
}
// Condition for "Student Passenger"
else if (passengerType.equalsIgnoreCase("Student"))
{
if (distance <= 10)
{
finalFare = 20 - (20 * 0.20);
System.out.println("Your Fare is: "+ finalFare);
}
else if (distance > 10)
{
fare1 = ((distance - 10) * 2.50);
finalFare = fare1 + 20 - ((fare1 + 20) * 0.20);
System.out.println("Your Fare is: "+finalFare);
}
}
// Condition for "Senior Passenger"
else if (passengerType.equalsIgnoreCase("Senior"))
{
if (distance <= 10)
{
finalFare = 20 - (20 * 0.30);
System.out.println("Your Fare is: "+ finalFare);
}
else if (distance > 10)
{
fare1 = ((distance - 10) * 2.50);
finalFare = fare1 + 20 - ((fare1 + 20) * 0.30);
System.out.println("Your Fare is: "+ finalFare);
}
}
}
}

How to return Scanner.in value from the method to another method

I want to make some simple program which will count monthly rate of product. There is two inputs: cost of the product - between 100-10000 and number of rates - between 6-48. I wanted to do it like in the code below:
import java.util.Scanner;
public class Calculator {
Scanner sc = new Scanner (System.in);
double productCost;
int numberOfRates;
double loanInterestRate;
double monthlyRate;
Double print () {
Calculator c = new Calculator();
System.out.println ("Enter the value of your product from 100 to 10 000 : ");
productCost=sc.nextDouble();
if (productCost < 100){
System.out.println ("You have to choose price between 100 to 10000. Try again: ");
c.print();
} else if (productCost >10000){
System.out.println ("You have to choose price between 100 to 10000. Try again: ");
c.print();
} else if (productCost >= 100 || productCost <=10000){
c.print1();
return = productCost;
// how to return productCost to be used in next method print1()?
}
else return null;
}
void print1(){
Calculator c = new Calculator();
System.out.println ("Now enter how many rates do you want to pay from 6 to 48: ");
numberOfRates=sc.nextInt();
if (numberOfRates<6){
System.out.println ("You can't choose this number of rates. Choose between 6-48: ");
c.print1();
} else if (numberOfRates>48){
System.out.println ("You can't choose this number of rates. Choose between 6-48: ");
c.print1();
} else if (numberOfRates>=6 || numberOfRates<=12) {
loanInterestRate=1.025;
monthlyRate = (productCost*loanInterestRate)/numberOfRates;
System.out.printf("Your monthly rate is: "+ "%.2f%n",monthlyRate);
} else if (numberOfRates>=13 || numberOfRates <=24 ) {
loanInterestRate=1.05;
monthlyRate = (productCost*loanInterestRate)/numberOfRates;
System.out.printf("Your monthly rate is: "+ "%.2f%n",monthlyRate);
} else if (numberOfRates >=25|| numberOfRates<=48){
loanInterestRate=1.1;
monthlyRate = (productCost*loanInterestRate)/numberOfRates;
System.out.printf("Your monthly rate is: "+ "%.2f%n",monthlyRate);
}
}
}
And the main method only calling the method from the other class.
public class MonthlyRate {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.print();
// TODO code application logic here
}
}
And what is the problem, I don't know how to return the "double productCost" from the method "print()". productCost is taking from the input and this is double but NetBeans showing me that it's not correct type. Can anybody help me understand where is the problem?
Simply do
return productCost;
return is a keyword, not a variable. It 'returns' the given value and exits the function, so that the entity calling the function can do this:
public static void main(String[] args) {
...
double cost = calc.print(); // note calc.print() PRODUCES a value, which we assign to `cost`
...
}
You can then do whatever you want with cost (or whatever you choose to name the variable), including passing it to another function.
Your program needs changes in a few places. I have done those changes and written below the updated program:
import java.util.Scanner;
class Calculator {
Scanner sc = new Scanner(System.in);
double productCost;
int numberOfRates;
double loanInterestRate;
double monthlyRate;
void print() {
Calculator c = new Calculator();
System.out.println("Enter the value of your product from 100 to 10 000 : ");
productCost = sc.nextDouble();
if (productCost < 100) {
System.out.println("You have to choose price between 100 to 10000. Try again: ");
c.print();
} else if (productCost > 10000) {
System.out.println("You have to choose price between 100 to 10000. Try again: ");
c.print();
} else if (productCost >= 100 || productCost <= 10000) {
print1(productCost);
}
}
void print1(double productCost) {
Calculator c = new Calculator();
System.out.println("Now enter how many rates do you want to pay from 6 to 48: ");
numberOfRates = sc.nextInt();
if (numberOfRates < 6) {
System.out.println("You can't choose this number of rates. Choose between 6-48: ");
c.print1(productCost);
} else if (numberOfRates > 48) {
System.out.println("You can't choose this number of rates. Choose between 6-48: ");
c.print1(productCost);
} else if (numberOfRates >= 6 || numberOfRates <= 12) {
loanInterestRate = 1.025;
monthlyRate = (productCost * loanInterestRate) / numberOfRates;
System.out.printf("Your monthly rate is: " + "%.2f%n", monthlyRate);
} else if (numberOfRates >= 13 || numberOfRates <= 24) {
loanInterestRate = 1.05;
monthlyRate = (productCost * loanInterestRate) / numberOfRates;
System.out.printf("Your monthly rate is: " + "%.2f%n", monthlyRate);
} else if (numberOfRates >= 25 || numberOfRates <= 48) {
loanInterestRate = 1.1;
monthlyRate = (productCost * loanInterestRate) / numberOfRates;
System.out.printf("Your monthly rate is: " + "%.2f%n", monthlyRate);
}
}
}
public class MonthlyRate {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.print();
// TODO code application logic here
}
}
It is easy to understand the changes after comparing your program with this updated program. Nevertheless, feel free to let me know if you need any further help on this.

Beginner Java: How to get it to display menu again after "Invalid selection"

How can I get it to display menu again after it displays "invalid selection"?
For now when a number < 1 or > 4 is entered, it just displays "Invalid selection."
Ideally I would want it to display
"Invalid selection
/nMETER CONVERSION
1) Convert to Kilometers
2) Convert to Inches
3) Convert to Feet
4) Quit the Program
Please make a selection:"
Here is my code
import java.util.Scanner;
import java.text.DecimalFormat;
public class Homework8bbb
{
//create main
public static void main(String[]args)
{//open main method
int selection;
double meters;
Scanner keyboard = new Scanner(System.in);
DecimalFormat format = new DecimalFormat("##.00");
//call showMenu method
//DISPLAY showMenu method
do
{
showMenu();
//get user [selection]
selection = keyboard.nextInt();
//validate selection
do {
if (selection < 1 || selection > 4)
{
System.out.print("Invalid selection\n");
selection = keyboard.nextInt();
}
}while(selection < 1 || selection > 4);
//get [meters]
System.out.print("How many meters?\n");
meters = keyboard.nextInt();
//validate meters: do not allow negative meters
while (meters < 0)
{
System.out.print("Invalid Selection. Please enter a positive number:\n");
meters = keyboard.nextInt();
}
switch (selection)
{
case 1: calcKilometers(meters);
break;
case 2: calcInches(meters);
break;
case 3: calcFeet(meters);
break;
case 4:
break; }
}while(selection != 4);
}
public static void showMenu()
{
System.out.print("\n"
+ "METER CONVERSION\n"
+ " 1) Convert to Kilometers\n"
+ " 2) Convert to Inches\n"
+ " 3) Convert to Feet\n"
+ " 4) Quit the Program\n"
+ " Please make a selection:\n");
}
//calcKilometers method
public static double calcKilometers(double meters)
{
double kilometers;
kilometers = meters * 0.001;
System.out.println(meters + " meters is " +
kilometers + " kilometers.");
return kilometers;
}
//calcInches method
public static double calcInches(double meters)
{
double inches;
inches = meters * 39.37;
System.out.println(meters + " meters is " +
inches + " inches.");
return inches;
}
//calcFeet method
public static double calcFeet(double meters)
{
double feet;
feet = meters * 3.281;
System.out.println(meters + " meters is " +
feet + " feet.");
return feet;
}
}//close class
You dont need this loop
do {
if (selection < 1 || selection > 4)
{
System.out.print("Invalid selection\n");
continue;
}
}while(selection < 1 || selection > 4);
replace it with this
if (selection < 1 || selection > 4) {
System.out.print("Invalid selection\n");
continue;
}
if you enter if statment continue will take you to the start of the loop

Java Coding - Program hangs when run

I am running into an issue with my Java code and I know where the issue lies, but I can't seem to figure out what I need to do to correct it. Can someone please help? This is the line that is causing the issue and I'm not sure how to fix it. subtotal = sc.nextDouble();
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;
public class InvoiceApp
{
private static double subtotal;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
// get the input from the user
String customerType = getValidCustomerType(sc);
try
{
System.out.print("Enter subtotal: ");
subtotal = sc.nextDouble();
}
catch (InputMismatchException e)
{
sc.next();
System.out.println("Error! Invalid number. Try again. \n");
continue;
}
// get the discount percent
double discountPercent = 0.0;
double subtotal = sc.nextDouble();
if (customerType.equalsIgnoreCase("R"))
{
if (subtotal < 100)
discountPercent = 0;
else if (subtotal >= 100 && subtotal < 250)
discountPercent = .1;
else if (subtotal >= 250)
discountPercent = .2;
}
else if (customerType.equalsIgnoreCase("C"))
{
if (subtotal < 250)
discountPercent = .2;
else
discountPercent = .3;
}
else
{
discountPercent = .1;
}
// calculate the discount amount and total
double discountAmount = subtotal * discountPercent;
double total = subtotal - discountAmount;
// format and display the results
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
System.out.println(
"Discount percent: " + percent.format(discountPercent) + "\n" +
"Discount amount: " + currency.format(discountAmount) + "\n" +
"Total: " + currency.format(total) + "\n");
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
private static String getValidCustomerType(Scanner sc)
{
String customerType = "";
boolean isValid = false;
while (isValid == false)
{
System.out.print("Enter customer type (r/c): ");
customerType = sc.next();
if (!customerType.equalsIgnoreCase("r") && !customerType.equalsIgnoreCase("c"))
{
System.out.println("Invalid customer type. Try again. \n");
}
else
{
isValid = true;
}
sc.nextLine();
}
return customerType;
}
}
Program does not hang when it executes:
subtotal = sc.nextDouble();
rather it simply waits for a double value input from the console. Input a value, and the rest of your program magic should follow.
The issue is that you have an extra call that scans the subtotal there.
One in the try-catch block
try
{
System.out.print("Enter subtotal: ");
subtotal = sc.nextDouble();
}
and then another one right before you calculate the discountPercent
// get the discount percent
double discountPercent = 0.0;
double subtotal = sc.nextDouble();
This is what's making you enter the amount twice. Just remove the second call and the program should run fine.

Is there a way to use words instead of numbers as outputs?

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 );
}
}

Categories

Resources