Having troubles with doubles - java

after long hard work, I have finally completed (almost) my java menu program. However, I am having trouble getting my return change function to work at the end of my code. It is giving very odd numbers. Any ideas?
Code:
import java.io.*;
import java.text.*;
import java.util.*;
public class JavaBurger
{
public static double amountowed = 0;
public static double amount;
public static double amount1 = 0;
public static double amount2 = 0;
public static double amount3 = 0;
public static double amount4 = 0;
public static double amount5 = 0;
public static double amount6 = 0;
public static double amount7 = 0;
public static double amount8 = 0;
public static double amount9 = 0;
public static double amount10 = 0;
static ArrayList MenuItems = new ArrayList();
public static void main(String[] args)
{
InputStreamReader inp = null;
BufferedReader input = null;
int nOption = 0;
DecimalFormat x = new DecimalFormat("###.##");
try
{
inp = new InputStreamReader(System.in);
input = new BufferedReader(inp);
while(true)
{
System.out.println("Choose a Menu Option");
System.out.println("1. Burger - 13.49");
System.out.println("2. Pasta - 16.79");
System.out.println("3. Salad - 13.49");
System.out.println("4. Salmon - 18.99");
System.out.println("5. Chicken - 16.99");
System.out.println("6. Nachos - 13.99");
System.out.println("7. Soup - 6.99");
System.out.println("8. Fajitas - 18.49");
System.out.println("9. Ribs - 23.99");
System.out.println("10. Calamari-9.99");
System.out.println("11. Clear Order");
System.out.println("12. Finish Order");
System.out.println("\nChoose an option(1-12) >> ");
System.out.println("Subtotal: $" + x.format(amount));
System.out.println("Total: $" + x.format(amount * 1.13));
System.out.println("For error correction, choose an option and enter a negative value to void the item.");
nOption = Integer.parseInt(input.readLine());
switch(nOption)
{
case 1:
Burger(input);
break;
case 2:
Pasta(input);
break;
case 3:
Salad(input);
break;
case 4:
Salmon(input);
break;
case 5:
Chicken(input);
break;
case 6:
Nachos(input);
break;
case 7:
Soup(input);
break;
case 8:
Fajitas(input);
break;
case 9:
Ribs(input);
break;
case 10:
Calamari(input);
break;
case 11:
Clear(input);
break;
case 12:
Finish(input);
break;
}
}
}
catch(Exception exp)
{
}
}
private static void Burger(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many Burgers would you like? ");
int a = Integer.parseInt(input.readLine());
double aaa = Math.pow(1 + a, a);
amount1 = (a * 13.49);
amount += amount1;
break;
}
}
private static void Pasta(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many orders of Pasta would you like? ");
int b = Integer.parseInt(input.readLine());
double bbb = Math.pow(1 + b, b);
amount2 = (bbb * 16.79);
amount += amount2;
break;
}
} private static void Salad(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many Salads would you like? ");
int c = Integer.parseInt(input.readLine());
double ccc = Math.pow(1 + c, c);
amount3 = (ccc * 13.49);
amount += amount3;
break;
}
} private static void Salmon(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many orders of Salmon would you like? ");
int d = Integer.parseInt(input.readLine());
double ddd = Math.pow(1 + d, d);
amount4 = (ddd * 18.99);
amount += amount4;
break;
}
} private static void Chicken(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many orders of Chicken would you like? ");
int e = Integer.parseInt(input.readLine());
double eee = Math.pow(1 + e, e);
amount5 = (eee * 16.99);
amount += amount5;
break;
}
} private static void Nachos(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many orders of Nachos would you like? ");
int f = Integer.parseInt(input.readLine());
double fff = Math.pow(1 + f, f);
amount6 = (fff * 13.99);
amount += amount6;
break;
}
} private static void Soup(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many orders of Soup would you like? ");
int g = Integer.parseInt(input.readLine());
double ggg = Math.pow(1 + g, g);
amount7 = (ggg * 6.99);
amount += amount7;
break;
}
} private static void Fajitas(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many orders of 2 Fajitas would you like? ");
int h = Integer.parseInt(input.readLine());
double hhh = Math.pow(1 + h, h);
amount8 = (hhh * 18.49);
amount += amount8;
break;
}
} private static void Ribs(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many racks of Ribs would you like? ");
int i = Integer.parseInt(input.readLine());
double iii = Math.pow(1 + i, i);
amount9 = (iii * 23.99);
amount += amount9;
break;
}
} private static void Calamari(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many orders of Calamari would you like? ");
int j = Integer.parseInt(input.readLine());
double jjj = Math.pow(1 + j, j);
amount10 = (jjj * 9.99);
amount += amount10;
break;
}
} private static void Clear(BufferedReader input) throws IOException
{
while(true)
{
amount = 0;
break;
}
} private static void Finish(BufferedReader input) throws IOException
{
while(true)
{
DecimalFormat x = new DecimalFormat("###.##");
System.out.println("Amount Due");
System.out.println("**********");
System.out.println("Subtotal:" + x.format(amount));
System.out.println("Total:" + x.format(amount * 1.13));
System.out.println("Please enter the amount tendered");
int k = Integer.parseInt(input.readLine());
double kk = Math.pow(1 + k, k);
amountowed = ((amount * 1.13) - kk);
if(amountowed == 0)
{
System.out.println("Thanks for paying with exact change!");
System.exit(0);
}
else if(amountowed < 0)
{
System.out.println("Change due:" + x.format(amountowed * -1.00));
System.exit(0);
}
else
{
System.out.println("Amount still owed:" + x.format(amountowed * -1.00));
}
}
}
}
Result:
Choose a Menu Option
1. Burger - 13.49
2. Pasta - 16.79
3. Salad - 13.49
4. Salmon - 18.99
5. Chicken - 16.99
6. Nachos - 13.99
7. Soup - 6.99
8. Fajitas - 18.49
9. Ribs - 23.99
10. Calamari-9.99
11. Clear Order
12. Finish Order
Choose an option(1-12) >>
Subtotal: $0
Total: $0
For error correction, choose an option and enter a negative value to void the it
em.
1
How many Burgers would you like?
1
Choose a Menu Option
1. Burger - 13.49
2. Pasta - 16.79
3. Salad - 13.49
4. Salmon - 18.99
5. Chicken - 16.99
6. Nachos - 13.99
7. Soup - 6.99
8. Fajitas - 18.49
9. Ribs - 23.99
10. Calamari-9.99
11. Clear Order
12. Finish Order
Choose an option(1-12) >>
Subtotal: $13.49
Total: $15.24
For error correction, choose an option and enter a negative value to void the it
em.
12
Amount Due
**********
Subtotal:13.49
Total:15.24
Please enter the amount tendered
100
Change due:270481382942152600000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000
Why am I getting wacky numbers for the change due?

Well... Is the following line needed here?
double kk = Math.pow(1 + k, k);
It completely messed up change computation, since you powered what the user inputs (k) + 1 to the kth power.
If you want to change it to a double, (double)k will do. Of course, for monetary computation, you'd better be using:
BigDecimal
cent based Integer / Long computation

I'm struggling to see why you're over-complicating your change computation so much.. Can't you simply compute amount tendered - total?

int e = Integer.parseInt(input.readLine());
double eee = Math.pow(1 + e, e);
Let's say I want 5 things.
double eee = Math.pow(1 + 5, 5)
This is 6 * 6 * 6 * 6 * 6 (i.e. a very big number). I think you just want a simple multiplication?

If you want a double from a string, use Double.parseDouble instead of Integer.parseInt. Do not do the extra pow calculation, that is making your results completely wrong.
More generally, throwing in random lines of code is rarely a good approach to compiler error reports. It is much better to understand what is going on, and deliberately fix that problem.
At some point, you will probably actually encounter floating point rounding error, and will again be advised to use BigDecimal instead of double.

First thing first ...
you dont need unneccessary while loops (Fixed in below code )
Math.pow(1 + a, a) not required.(Fixed in below code )
amount1 , amount 2 etc can be declared as Local variable (NOT Fixed in below code ) as it dont harm
private static void Burger(BufferedReader input) throws IOException
{
System.out.println("How many Burgers would you like? ");
int a = Integer.parseInt(input.readLine());
// double aaa = Math.pow(1 + a, a);// Why THis???
amount1 = ((double)a * 13.49);
amount += amount1;
}
private static void Pasta(BufferedReader input) throws IOException
{
System.out.println("How many orders of Pasta would you like? ");
int b = Integer.parseInt(input.readLine());
// double bbb = Math.pow(1 + b, b); You dont need this
amount2 = ((double)b * 16.79);
amount += amount2;
}
private static void Salad(BufferedReader input) throws IOException
{
System.out.println("How many Salads would you like? ");
int c = Integer.parseInt(input.readLine());
//double ccc = Math.pow(1 + c, c); No Need of this again
amount3 = ((double)c * 13.49);
amount += amount3;
}
} private static void Salmon(BufferedReader input) throws IOException
{
System.out.println("How many orders of Salmon would you like? ");
int d = Integer.parseInt(input.readLine());
//double ddd = Math.pow(1 + d, d); No Need
amount4 = ((double)d * 18.99);
amount += amount4;
}
private static void Chicken(BufferedReader input) throws IOException
{
System.out.println("How many orders of Chicken would you like? ");
int e = Integer.parseInt(input.readLine());
amount5 = ((double)e * 16.99);
amount += amount5;
}
private static void Nachos(BufferedReader input) throws IOException
{
System.out.println("How many orders of Nachos would you like? ");
int f = Integer.parseInt(input.readLine());
amount6 = ((double)f * 13.99);
amount += amount6;
}
private static void Soup(BufferedReader input) throws IOException
{
System.out.println("How many orders of Soup would you like? ");
int g = Integer.parseInt(input.readLine());
amount7 = ((double)g * 6.99);
amount += amount7;
}
private static void Fajitas(BufferedReader input) throws IOException
{
System.out.println("How many orders of 2 Fajitas would you like? ");
int h = Integer.parseInt(input.readLine());
amount8 = ((double)h * 18.49);
amount += amount8;
}
private static void Ribs(BufferedReader input) throws IOException
{
System.out.println("How many racks of Ribs would you like? ");
int i = Integer.parseInt(input.readLine());
amount9 = ((double)i * 23.99);
amount += amount9;
}
private static void Calamari(BufferedReader input) throws IOException
{
System.out.println("How many orders of Calamari would you like? ");
int j = Integer.parseInt(input.readLine());
amount10 = ((double)j * 9.99);
amount += amount10;
}
private static void Clear(BufferedReader input) throws IOException
{
amount = 0;
}
private static void Finish(BufferedReader input) throws IOException
{
amountowed =amount * 1.13
DecimalFormat x = new DecimalFormat("###.##");
while(amountowed >0)
{
System.out.println("Amount Due");
System.out.println("**********");
System.out.println("Subtotal:" + x.format(amount));
System.out.println("Total:" + x.format(amountowed));
System.out.println("Please enter the amount tendered");
double k = Double.parseDouble(input.readLine());
// double kk = Math.pow(1 + k, k); No Need
amountowed = (amountowed - k);
if(amountowed == 0)
{
System.out.println("Thanks for paying with exact change!");
System.exit(0);
}
else if(amountowed < 0)
{
System.out.println("Change due:" + x.format(amountowed * -1.00));
System.exit(0);
}
else
{
System.out.println("Amount still owed:" + x.format(amountowed));
}
}
}

Related

Convert temperature from Celsius to Fahrenheit using 3 functions

I'm new to java and I'm trying to write a program that converts Celsius to Fahrenheit
import java.util.Scanner;
public class Temps
{
public static void main(String[] args)
{
System.out.print("Enter temp(70 f or 20 c): ");
double temp = keyboard.nextDouble();
String units = keyboard.next();
if (units.equal("f"))
newtemp = ftoc(temp);
else if (units.equals("c"))
newtemp = ctof(temp);
else System.err.println("units must be c or f");
}
public static double ftoc (int c)
return (( 5.0 / 9.0) * (c - 32));
}
public static double ctof (int f)
{
return ((9.0/5.0)* f+32);
}
}
can someone explain to me what I did wrong.
Quite a few problems
see comments in fixed code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter temp(70 f or 20 c): ");
double temp = keyboard.nextDouble();
String units = keyboard.next();
double newtemp = -1; // not declared
if (units.equals("f")) // should be equals
newtemp = ftoc(temp);
else if (units.equals("c"))
newtemp = ctof(temp);
else System.err.println("units must be c or f");
System.out.println("the new temp is " + newtemp); // need to print it out
}
public static double ftoc (double c) { // take a double
return (( 5.0 / 9.0) * (c - 32));
}
public static double ctof (double f) // take a double
{
return ((9.0/5.0)* f+32);
}

Receiving Infinity Value

I'm trying to make a unit conversion program but I keep receiving value as infinity. I'm not sure where I need to fix since it's not giving me errors. I only tested oz to ml to make sure I'm doing it correctly but I'm receiving infinity as the answer.
UnitConverter.java:
public class UnitConverter {
final double oz_TO_ml = 29.5735;
final double gal_TO_g = 3.78541;
final double lb_TO_kg = 0.453592;
final double inc_TO_mm = 25.4;//Inc is inches
final double ft_TO_cm = 30.48;
final double mi_TO_km = 1.60934;
double factor;
public UnitConverter(String unit) {
if (unit.equals("oz")) {
factor = oz_TO_ml;
} else if (unit.equals("gal")) {
factor = gal_TO_g;
} else if (unit.equals("lb")) {
factor = lb_TO_kg;
}
}
public double toOz(double amount) {
return (amount * factor);
}
public double fromOz(double amount) {
return (amount / factor);
}
public double toMl(double amount) {
return (amount * factor);
}
public double fromMl(double amount) {
return (amount / factor);
}
}
Calculator.java:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
System.out.print("Convert to: ");
String toUnit = in.nextLine();
UnitConverter from = new UnitConverter(fromUnit);
UnitConverter to = new UnitConverter(toUnit);
System.out.print("Value ");
double val = in.nextDouble();
double oz = from.toOz(val);
double converted = to.fromOz(oz);
System.out.println(val + " " + fromUnit + " = " + converted + " " + toUnit);
}
}
Sample input:
Convert from: oz
Convert to: ml
Value 12
Output:
12.0 oz = Infinity ml
Initialize the factor varible with one. A java with default give 0 to primitive double,
class UnitConvertor {
final double oz_TO_ml = 29.5735;
final double gal_TO_g = 3.78541;
final double lb_TO_kg = 0.453592;
final double inc_TO_mm = 25.4;//Inc is inches
final double ft_TO_cm = 30.48;
final double mi_TO_km = 1.60934;
double factor=1;//initialize with 1
But I am still not sure that what is the check you are using if the user input is 'ml'.
public UnitConverter(String unit)
{
if (unit.equals("oz"))
{
factor = oz_TO_ml;
} else if (unit.equals("gal"))
{
factor = gal_TO_g;
} else if (unit.equals("lb"))
{ factor = lb_TO_kg;
}
}
If you pass "ml" the factor will be zero
Your design currently needs two of these but you really only need one as "oz" has everything it needs to do the conversion.
Ignore the the toUnit in your line input code and just use fromUnit
Edit : I'll show you an alternative way to do things, it just supports one convert to show the rough design. Note the method calls are now static because you will only ever need one instance of them
UnitConverter.java
public class UnitConverter
{
private static final double oz_TO_ml = 29.5735;
public static double convert(String fromType, String toType,double amount) throws IllegalArgumentException
{
if (fromType.equals("oz") && toType.equals("ml"))
{
return (amount * oz_TO_ml);
}
else
{
throw new IllegalArgumentException("The combination of converting " + fromType + " to " + toType + " is not supported");
}
}
}
Calculator.java:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
System.out.print("Convert to: ");
String toUnit = in.nextLine();
System.out.print("Value ");
double val = in.nextDouble();
System.out.println(val + " " + fromUnit + " = " + UnitConverter.convert(fromUnit,toUnit,val) + " " + toUnit);
}
}
Your UnitConverter class constructor only knows about 3 units: oz, gal, and lb. If you instantiate it with one of those, it will correctly assign the factor and be able to convert units, as seen below:
public UnitConverter(String unit) {
if (unit.equals("oz")) {
factor = oz_TO_ml;
} else if (unit.equals("gal")) {
factor = gal_TO_g;
} else if (unit.equals("lb")) {
factor = lb_TO_kg;
}
}
However, in your Calculator class, you have this line:
UnitConverter from = new UnitConverter(fromUnit);
UnitConverter to = new UnitConverter(toUnit);
If you run your program with your sample input, from is oz and to is ml. But if you instantiate UnitConverter with the unit ml, what does factor get set to? According to your constructor, it is never set, and so it retains its default value of 0.0.
Later, you call this line:
double converted = to.fromOz(oz);
This runs the fromOz method
public double fromOz(double amount) {
return (amount / factor);
}
Which divides by the factor, which is 0.0. This is the source of your Infinity output.
As the other answer says, you don't need to have two UnitConverter objects to perform this calculation. The factor is correct to convert between ounces and millilitres, so this Calculator code is sufficient.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
UnitConverter from = new UnitConverter(fromUnit);
System.out.print("Value ");
double val = in.nextDouble();
double result = from.toMl(val);
System.out.println(val + " " + fromUnit + " = " + result + " ml.");
}
}
If you wanted to keep your current calculator code, you would need to add a condition in your UnitConverter constructor for a scalefactor for ml (1.0). However, I think this approach is flawed because what happens, for example, when you try to convert between oz and inches? The conversion makes no sense but your architecture would not prevent it.

Restaurant Menu: how to efficiently implement a nested loop to collect user input and conduct error checking

I have these two methods which I cant quite figure out the best way to go about their algorithm.
I am writing a program that acts like a restaurant menu and collects user order.
The implementation is,
welcome user and present him with the menu
while the user has not entered 'q', send the user input to a method called getGoodOrderLine(String str)
this method will then check the input for the following,
- First, it must check that a number is present before trying to read it; if there is no number, the entry is an error unless it starts with ‘q’ or ‘Q’, which tells the program to quit.
- then, determine which item the user is asking for by looking at just the first letter. So an input “2 Hello” means 2 hamburgers. the assumption is that if there is a digit in the string, the digit appears before the word, for simplicity
- finally, if the first letter is not (H,C,F or D), print an error message and ask that it be re-entered.
My problem is that, I created a while loop that should loop until the user input is valid, but it doesn't seem to be working, here is my code:
import java.util.*;
public class MenuApp
{
//global variables
public static double HAM = 3.75;
public static double CHEESE = 4.10;
public static double FRIES = 2.50;
public static double DRINKS = 1.75;
public static void main(String [] args)
{
//variables
String order;
double total = 0.0;
boolean stopLoop;
//print welcome message && collect order
welcomeCustomer();
order = collectItem();
order = getGoodOrderLine(order);
stopLoop = order.equalsIgnoreCase("q");
while(!stopLoop)//while user hasnt typed q
{
if(order.equalsIgnoreCase("q"))
{
break;
}
order = getGoodOrderLine(order);
//will add the value of user order to total here if order is valid
//leave loop if useer inputs q
}
//ending program
Date today = new Date();
System.out.println("Date: " + today);
System.out.println("Please pay " + total + "\n");
System.out.println("End of processing");
}
public static void welcomeCustomer()
{
System.out.println("Welcome to QuickieBurger!");
System.out.println("Hamburgers \t\t $" + HAM);
System.out.println("cheeseBurgers\t\t $" + CHEESE);
System.out.println("Fries\t\t\t $" + FRIES);
System.out.println("Drinks\t\t\t $" + DRINKS+"\n");
}
public static String collectItem()
{
String userInput = null;
Scanner kbd = new Scanner(System.in);
System.out.println("Please place your order (e.g., 3 ham). Enter Q to quit.");
userInput = kbd.nextLine();
System.out.println(userInput);
return userInput;
}
public static String getGoodOrderLine(String userInput)
{
String result = "";
boolean pass = false;
if(userInput.equalsIgnoreCase("q"))
{
return userInput;//early exit, return q
}
//check if it has at least a digit first
for(char c: userInput.toCharArray())
{
if(Character.isDigit(c))
{pass = true;}
}
//if it doesn't have a digit || string doesnt begin with a digit
if(!Character.isDigit(userInput.charAt(0)))
{
if(!pass)
System.out.println("Your entry "+ userInput + " should specify a quantity");
else
System.out.println("Your entry "+ userInput + " does not begin with a number");
}
else
{
//do the remaining tests here
}
return result;
}
}
I keep getting null pointer and index out of bounds exceptions when testing for Character.isDigit(userInput.charAt(0));
the problem is you are returning empty string so charAt(0) give error since char array has no elements.and if you want to collect items you need to use a collection type like list and u can't use a array since array has fixed length.and to get price of user input product you need to map prices with product names .so u can use map.but i used 2 arrays which act as a map.check this and it's output.
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.Scanner;
public class myMenu {
public static String names[] = {"HAM", "CHEESE", "FRIES", "DRINKS"};
public static double prices[] = {3.75, 4.10, 2.50, 1.75};
public static ArrayList<List<String>> allitems = new ArrayList<>();
static double total = 0.0;
public static void main(String[] args) {
welcomeCustomer();
collectItem();
}
public static void welcomeCustomer() {
System.out.println("Welcome to QuickieBurger!");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + "\t\t\t" + prices[i]);
}
}
public static void collectItem() {
String userInput = "";
Scanner kbd = new Scanner(System.in);
System.out.println("Please place your order (e.g., 3 ham). Enter Q to quit.");
userInput = kbd.nextLine();
while (!getGoodOrderLine(userInput)) {
userInput = kbd.nextLine();
}
}
private static boolean getGoodOrderLine(String userInput) {
if (userInput.equalsIgnoreCase("q")) {
transaction();
} else if (!Character.isDigit(userInput.charAt(0))) {
System.out.println("quesntity should be specified. try again");
return false;
} else {
for (int i = 0; i < names.length; i++) {
String items = names[i];
//get the first charactor from userinput
char c = 0;
for(int z=0;z<userInput.length();z++){
c=userInput.charAt(z);
if(Character.isAlphabetic(c)){
break;
}
}
if (Character.toLowerCase(items.charAt(0)) ==Character.toLowerCase(c)) {
String s="";
int x=0;
while(Character.isDigit(userInput.charAt(x))){
s+=userInput.charAt(x);
x++;
}
int quentity=Integer.parseInt(s);
double pri = prices[i];
double sub = quentity * pri;
total += sub;
ArrayList<String> subitem = new ArrayList<>();
subitem.add(items);
subitem.add(String.valueOf(quentity));
subitem.add(String.valueOf(sub));
allitems.add(subitem);
return false;
}
}
System.out.println("this not a valid food item.try again");
}
return false;
}
private static void transaction() {
//ending program
Date today = new Date();
System.out.println("-------------------------------------");
System.out.println("Date: " + today);
for (List<String> menu : allitems) {
System.out.println(menu.get(0)+" "+menu.get(1)+" = "+menu.get(2));
}
System.out.println("Please pay " + total + "\n");
System.out.println("------------------------------------");
System.out.println("End of processing");
}
}
output>>
Welcome to QuickieBurger!
HAM 3.75
CHEESE 4.1
FRIES 2.5
DRINKS 1.75
Please place your order (e.g., 3 ham). Enter Q to quit.
2 Hello
4 CHEESE
q
-------------------------------------
Date: Sun Nov 02 02:59:56 PST 2014
HAM 2 = 7.5
CHEESE 4 = 16.4
Please pay 23.9
------------------------------------
End of processing
public class MenuApp
{
// global variables
public static double HAM = 3.75;
public static double CHEESE = 4.10;
public static double FRIES = 2.50;
public static double DRINKS = 1.75;
// you need to define errors
public static String noInput = "__MENUAPP_ERROR_1";
public static String invalidInput = "__MENUAPP_ERROR_2";
...
public static String getGoodOrderLine(String userInput)
{
String result = "";
boolean pass = false;
boolean startWithDigit = false;
// add this line to verify the input first
if (userInput == null || userInput.equalsIgnoreCase(""))
{
return MenuApp.noInput ;
}
if(userInput.equalsIgnoreCase("q"))
{
return "q"; // early exit, return q
}
//check if it has at least a digit first
for(char c: userInput.toCharArray())
if(Character.isDigit(c))
pass = true;
startWithDigit = Character.isDigit(userInput.charAt(0));
// if it doesn't have a digit || string doesnt begin with a digit
if(!startWithDigit)
{
if(!pass)
System.out.println("Your entry "+ userInput + " should specify a quantity");
else
System.out.println("Your entry "+ userInput + " does not begin with a number");
return MenuApp.invalidInput;
}
else
{
// do the remaining tests here
}
return result;
}
}

Simulating a gas station

So I'm supposed to create a program where I have a gas station with 5 gas pumps and and I don't know how to keep track of the statistics, the program correctly subtracts the amount of gas left from the type of gas tank but when the next customer pumps gas the statistics get erased? any help would be appreciated, here is my code. keep in my mind this is part of a 5 class program and this is only one part.
import java.util.Random;
import java.util.Scanner;
public class GasPump
{
static Scanner Input = new Scanner (System.in);
private static double totalRevenue;
private static double currentPurchase;
//private int currentGasType;
private static double currentGasType;
private static double currentGasAmount;
private Client currentClient;
private int clock;
private static double regularTank;
private static double plusTank;
private static double supremeTank;
//private static double amountLeftInTank;
public void updatePump()
{
if (currentClient != null)
{
clock--;
if (clock == 0)
{
//totalRevenue += currentPurchase;
totalRevenue = totalRevenue + currentPurchase;
resetPump ( );
}
}
}
public void resetPump ( )
{
clock = 0;
currentClient = null;
currentPurchase = 0;
//currentGasType = "";
currentGasType = 0;
currentGasAmount = 0;
}
public boolean pumpOpen()
{
return (clock == 0) && (currentClient == null);
}
public static double getCurrentGasType()
{
regularTank = 1000;
plusTank = 1000;
supremeTank = 1000;
//Scanner Input = new Scanner(System.in);
System.out.println("What type of gas would you like?");
System.out.println("Regular , Plus or Premium");
System.out.println("1)Regular: $2.99 per gallon; 2)Plus: $3.99 per gallon; 3)Premium: $4.99 per gallon");
currentGasType = Input.nextDouble();
Random gen = new Random ();
//currentGasAmount = gen.nextDouble ()* 45;
currentGasAmount = gen.nextDouble()*50;
double roundOff = (double) Math.round(currentGasAmount * 100) / 100;
//System.out.println("How many gallons would you like?");
//currentGasAmount = Input.nextDouble();
if (currentGasType == 1)
{
currentGasType = 2.99;
regularTank = regularTank - currentGasAmount;
}
else if (currentGasType == 2)
{
currentGasType = 3.99;
plusTank = plusTank - currentGasAmount;
}
else
{
currentGasType = 4.99;
supremeTank = supremeTank - currentGasAmount;
}
System.out.println("# of gallons purchased: " + currentGasAmount);
System.out.println("Amount of regular gas left: " + regularTank);
System.out.println("Amount of plus gas left: " + plusTank);
System.out.println("Amount of supreme gas left: " + supremeTank);
return currentGasType;
}
/*public static double getCurrentGasAmount() {
Random gen = new Random ();
currentGasAmount = gen.nextDouble ()* 50;
//System.out.println("How many gallons would you like?");
//currentGasAmount = Input.nextDouble();
System.out.println("# of gallons purchased: " + currentGasAmount);
return currentGasAmount;
}
*/
public static double getCurrentPurchase()
{
currentPurchase = currentGasType * currentGasAmount;
return currentPurchase;
}
public static double getTotalRevenue() {
totalRevenue += currentPurchase;
System.out.println("Total revenue so far is " + totalRevenue);
return totalRevenue;
}
/*public static double getAmountLeftInTank()
{
regularTank = 1000;
plusTank = 1000;
supremeTank = 1000;
if (currentGasAmount == 1)
if (currentGasType == 1)
{
//regularTank = regularTank - currentGasAmount;
}
else if (currentGasType == 2)
else if (currentGasAmount == 2)
{
//plusTank = plusTank - currentGasAmount;
}
else
{
supremeTank = supremeTank - currentGasAmount;
}
System.out.println("Amount of regular gas left: " + regularTank);
System.out.println("Amount of plus gas left: " + plusTank);
System.out.println("Amount of supreme gas left: " + supremeTank);
return amountLeftInTank;
}
*/
public void serveAClient (Client aClient)
{
clock = 10;
currentClient = aClient;
GasPump.getCurrentGasType();
System.out.println("Your total is " + GasPump.getCurrentPurchase());
GasPump.getTotalRevenue();
//GasPump.getAmountLeftInTank();
/*
* design get methods
* ask client what type of gas he wants
* add more code here
*/
// add the total here
}
}
Don't use static fields for the data stored in GasPump.
static fields are singletons, they only have a single value shared across all instances of GasPump. This means that if you have multiple instances of GasPump, then calling reset will reset all of the gas pumps.
By removing the keyword static from each of the fields, then there will be a separate copy of the field held for each of the GasPump's. And thus calling reset will only wipe the fields for that one instance of GasPump.
The following diagram may help you to visualise the difference:
In this example, count has been shared across instances c1 and c2 of CircleWithCount.
You can read more detail about using the static keyword on fields here: What does the 'static' keyword do in a class?

Calculation of pi with an infinite series

I approximate pi with this series:
pi = 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ...
My code is in the loop. When I enter the first time in loop, the result is exactly what I want, but at the second time it is not.
package pi_number;
import java.util.Scanner;
public class Pi_number {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
double pi=0.0;
double termx=0.0;
System.out.print("Enter any key to start or E stop: ");
String Exit=input.next();
while (!Exit.equals("E"))
{
System.out.print("How many term do you want : ");
int term=input.nextInt();
for(int i=1;i<=term; i++)
{
if(i%2==0)
{
termx=(double)-4/(2*i-1);
}
else
{
termx=(double)4/(2*i-1);
}
pi+= termx;
}
System.out.println("Pi number equals="+pi);
System.out.print("Enter any key to start or E stop: ");
Exit=input.next();
}
}
}
You need to initialize termx and pi before calculation loop:
while (!Exit.equals("E"))
{
termx = 0.0; //initial
pi = 0.0; //initial
System.out.print("How many term do you want : ");
int term=input.nextInt();
for(int i=1;i<=term; i++)
{
if(i%2==0)
{
termx=(double)-4/(2*i-1);
}
else
{
termx=(double)4/(2*i-1);
}
pi+= termx;
}
System.out.println("Pi number equals="+pi);
System.out.print("Enter any key to start or E stop: ");
Exit=input.next();
}
Initialize your pi and terms before starting to calculate your pi.
Try this code :
package pi_number;
import java.util.Scanner;
public class Pi_number {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double pi,termx;
System.out.print("Enter any key to start or E stop: ");
String Exit = input.next();
while (!Exit.equals("E")) {
System.out.print("How many term do you want : ");
int term = input.nextInt();
pi=0.0;
termx=0.0;
for (int i = 1; i <= term; i++) {
if (i % 2 == 0) {
termx = (double) -4 / (2 * i - 1);
} else {
termx = (double) 4 / (2 * i - 1);
}
pi += termx;
}
System.out.println("Pi number equals=" + pi);
System.out.print("Enter any key to start or E stop: ");
Exit = input.next();
}
}
}

Categories