I've written a code that supposed to count the change(number of dollars bills, dimes coins, pennies ....). only "pennies" work, but not the way it supposed to be, all the rest lines of code never responds.
public BigDecimal deposit() {
String money = io.readString("Please, deposit money");
BigDecimal deposit = new BigDecimal(money);
return deposit;
}
public void change(String itemId) throws VendingMachinePersistenceException {
Change change = new Change();
Item item = dao.getItem(itemId);\\this line works
BigDecimal change1 = deposit().subtract(item.getPrice());\\this line works
int changeBack = change1.intValue();
io.print("Your change is : ");
change = change.remainder(new BigDecimal("100"));
if (changeBack/100 != 0) {
change.setDollars(changeBack/100);
changeBack = changeBack%100;
io.print(change.getDollars() + " dollars, ");
}
if (changeBack/25 != 0) {
change.setQuarters(changeBack/25);
changeBack = changeBack%25;
io.print(change.getQuarters() + " quarters, ");
}
if (changeBack/10 != 0) {
change.setDimes(changeBack/10);
changeBack = changeBack%10;
io.print(change.getDimes()+ " dimes, ");
}
if (changeBack/5!= 0) {
change.setNickels(changeBack/5);
changeBack = changeBack%5;
io.print(change.getNickels() + " nickels, ");
}
change.setPennies(changeBack);
io.print(change.getPennies()+ " pennies.");
}
It could be the issue with if statements or converting BigDecimal to Int. I'm not sure.
Please, help!
since you're using BigDecimal for money, change1 is probably holding a value like 5.21
converting that to an int will get you just 5 for changeBack, resulting in a nickel for change.
so you probably want to multiply the BigDecimal by 100 before converting it into an int.
Related
This is probably a dumb question. My following code looks fine but on the output, it does not expect results from my testing scenarios. Code follows:
import java.util.Scanner;
public class PartyPlannerLab {
public static Scanner input = new Scanner(System.in);
public static int getGuestCount(int guests) {
while(true) {
System.out.print("Enter number of guests: ");
guests = input.nextInt();
if (guests >= 1 && guests <= 100)
break;
else
System.out.println("The guest count must be at least 1, but does not exceed 100. Please enter again.");
}
return guests;
}
public static int getSlicesPerPerson(int slicesPerPerson) {
while(true) {
System.out.print("Enter number of slices per person: ");
slicesPerPerson = input.nextInt();
if (slicesPerPerson >= 1 && slicesPerPerson <= 8)
break;
else
System.out.println("The pizza slice count must be at least 1, but does not exceed 8. Please try again.");
}
return slicesPerPerson;
}
public static double computeRoomCost(int guests, double roomCost) {
if (guests <= 30)
roomCost = 100.00;
else
roomCost = 200.00;
return roomCost;
}
public static double computeSodaCost(double sodaCost, int guests) {
sodaCost = guests * 1.50;
return sodaCost;
}
public static void printSummary(int guests, double roomCost, double sodaCost, double pizzaCost) {
System.out.println("Total Guests: " + guests);
System.out.println("RoomCost: $" + roomCost);
System.out.println("SodaCost: $" + sodaCost);
System.out.println("PizzaCost: $" + pizzaCost);
System.out.println("Total Cost: $" +(roomCost + sodaCost + pizzaCost));
}
public static void main(String[] args) {
int guests = 0;
int slicesPerPerson = 0;
double roomCost = 0.0;
double sodaCost = 0.0;
double pizzaCost = 0.0;
getGuestCount(guests);
getSlicesPerPerson(slicesPerPerson);
computeRoomCost(guests, roomCost);
computeSodaCost(sodaCost, guests);
printSummary(guests, roomCost, sodaCost, pizzaCost);
input.close();
}
}
One output is as follows:
Enter number of guests: 10
Enter number of slices per person: 2
Total Guests: 0
RoomCost: $0.0
SodaCost: $0.0
PizzaCost: $0.0
Total Cost: $0.0
You are not making use of the return values of getGuestCount, getSlicesPerPerson etc.
Those methods return a value, which basically means that you can use them as if they are a value. input.nextInt returns a value too, which is why you can put it on the right of =.
Inside the method, getGuestCount seems to change the value of guests passed in, but this change won't actually reflect on the caller's side, because Java is pass-by-value. You are kind of throwing away the value that was passed in.
In fact, your methods will only work as they are if the arguments are passed by reference, so that the methods can modify the variables passed in. But this is not possible in Java. See this post for the difference between pass-by-value and pass-by-reference.
The right way to rewrite your methods in Java is to return the value (which they are already doing, but you are not making use of the return value), and remove the extraneous parameter.
public static int getGuestCount() {
int guests;
while(true) {
System.out.print("Enter number of guests: ");
guests = input.nextInt();
if (guests >= 1 && guests <= 100)
break;
else
System.out.println("The guest count must be at least 1, but does not exceed 100. Please enter again.");
}
return guests;
}
public static int getSlicesPerPerson() {
int slicesPerPerson;
while(true) {
System.out.print("Enter number of slices per person: ");
slicesPerPerson = input.nextInt();
if (slicesPerPerson >= 1 && slicesPerPerson <= 8)
break;
else
System.out.println("The pizza slice count must be at least 1, but does not exceed 8. Please try again.");
}
return slicesPerPerson;
}
public static double computeRoomCost(int guests) {
double roomCost;
if (guests <= 30)
roomCost = 100.00;
else
roomCost = 200.00;
return roomCost;
}
public static double computeSodaCost(int guests) {
double sodaCost = guests * 1.50;
return sodaCost;
}
This is how you "make use of the return values": instead of passing in the variable you want the method to modify, put it on the left hand side of = in an assignment statement:
guests = getGuestCount();
slicesPerPerson = getSlicesPerPerson();
roomCost = computeRoomCost(guests);
sodaCost = computeSodaCost(guests);
The reason why you are not getting the output is that the values that you initialized in your main method are not being updated with the method calls you are making.
Below code might solve the problem you are facing -
public static void main(String[] args) {
int guests = 0;
int slicesPerPerson = 0;
double roomCost = 0.0;
double sodaCost = 0.0;
double pizzaCost = 0.0;
guests = getGuestCount(guests);
slicesPerPerson = getSlicesPerPerson(slicesPerPerson);
roomCost = computeRoomCost(guests, roomCost);
sodaCost = computeSodaCost(sodaCost, guests);
printSummary(guests, roomCost, sodaCost, pizzaCost);
input.close();
}
Note- There is no need of passing the parameter in the methods getGuestCount & getSlicesPerPerson as the input is being taken from I/O
I got a little project that I had to complete for a job. I am sure you guys have seen this project on here. I am want two things, tip on how to get the correct answer and also a peer review on my solution so far.
public class OrderMethod {
static Map<String, BigDecimal> newOrder;
static final BigDecimal BASICSALES = new BigDecimal(.10);
static final BigDecimal IMPORTSALES = new BigDecimal(.05);
static final BigDecimal BASICANDIMPORTSALES = new BigDecimal(.15);
static final BigDecimal Rounding = new BigDecimal(0.05);
static BigDecimal total = new BigDecimal(0);
public void convertOrders() throws IOException {
ReadFile readfile = new ReadFile();
ArrayList<String> order = readfile.getFile();
newOrder = new LinkedHashMap<String, BigDecimal>();
for(String i : order) {
String[] splitOrder = i.split("at\\ ");
newOrder.put(splitOrder[0], new BigDecimal(splitOrder[1]));
}
}
public void calculate() {
newOrder.forEach((k, v) -> {
if(!((k.contains("chocolate")) || k.contains("book") || k.contains("pill")) && k.contains("import")){
v = v.multiply(BASICANDIMPORTSALES).add(v);
v = v.round(new MathContext(4));
System.out.println("Both " + k + " tax: $" + v);
newOrder.put(k, v);
}
else {
if(!(k.contains("chocolate")|| k.contains("book") || k.contains("pill"))) {
v = v.multiply(BASICSALES).add(v);
v = v.round(new MathContext(4));
System.out.println("Basic " + k + " tax: $" + v);
newOrder.put(k, v);
}
if(k.contains("import")) {
v = v.multiply(IMPORTSALES).add(v);
v = v.round(new MathContext(4));
System.out.println("Import " + k + " tax: $" + v);
newOrder.put(k, v);
}
}
total = total.add(v);
});
}
public void print() {
newOrder.forEach((k, v) -> {
System.out.println(k + ": $" + v);
});
System.out.println("Total: $" + total);
}
public static void main(String[] args) throws IOException {
OrderMethod om = new OrderMethod();
om.convertOrders();
om.calculate();
om.print();
}
}
So what I have done is that I have the program reading a text file containing inputs such as
Input 1:
1 book at 12.49
1 music CD at 14.99
1 chocolate bar at 0.85
Input 2:
1 imported box of chocolates at 10.00
1 imported bottle of perfume at 47.50
Input 3:
1 imported bottle of perfume at 27.99
1 bottle of perfume at 18.99
1 packet of headache pills at 9.75
1 box of imported chocolates at 11.25
These are the list of solutions:
Output:
Output 1:
1 book : 12.49
1 music CD: 16.49
1 chocolate bar: 0.85
Sales Taxes: 1.50
Total: 29.83
Output 2:
1 imported box of chocolates: 10.50
1 imported bottle of perfume: 54.65
Sales Taxes: 7.65
Total: 65.15
Output 3:
1 imported bottle of perfume: 32.19
1 bottle of perfume: 20.89
1 packet of headache pills: 9.75
1 imported box of chocolates: 11.85
Sales Taxes: 6.70
Total: 74.68
I am having a little problem with my calculation. No matter what my answers to Input 2 and 3 seems to be a couple of decimal places off. I get $65.12 for Input 2 and $74.64 for Input 3.
I want help on how to better round up my answers and also what do you think of my code so far.
I don't understand your code but I had to do this on my exam.
I use the operator % like this and it works.
if((number * 100)%10 >= 5)
To round up to 5 cents, you can these :
private static final BigDecimal TWENTY = new BigDecimal(20);
public BigDecimal roundUp5(BigDecimal value)
{
// The final setScale(2) is just to add the ".00" when you display
return value.multiply(TWENTY).setScale(0, BigDecimal.ROUND_CEILING).divide(TWENTY).setScale(2);
}
// You don't need this one as you're using BigDecimal; it's just for completeness!
public double roundUp5(double value)
{
return Math.ceil(value * 20) / 20;
}
Happy to provide my thoughts as a code review.
Firstly, why the separate convertOrders and calculate methods ? Creating the Map in convertOrders, and then iterating across it and re-inserting in calculate is messy and confusing.
Much better would be to have convertOrders call calculate as part of its iteration as each line is read, and therefore create each Map entry correctly as it goes.
You have some repeated expressions that I would refactor into methods for readability and prospect of future business changes, so :
public boolean isBasic(String itemName) {
String name = itemName.toLowerCase();
return !( name.contains("chocolate") || name.contains("book") || name.contains("pill") );
}
public boolean isImport(String itemName) {
String name = itemName.toLowerCase();
return name.contains("import");
}
In your if statements in calculate currently run as :
if (isBasic(k) && isImport(k)) {
// Basic and Import
} else {
if (isBasic(k)) {
}
if (isImport(k)) {
}
}
That flow is a bit confusing, and would be a pain to refactor if in future you needed to also handle non-basic and non-imported items.
There's some common code between all these if blocks, so I would move that out to after the if - which would leave the log statement and the setting of the multiplication factor the only lines remaining in the if blocks.
While we're talking about the multiplication factors, you have those set to values less than 1 (eg 0.15) ... bit then you add v to the result ! It would be much better to have the factors be > 1 and so get rid of the add(v).
Incidentally, it is also preferable to initialise BigDecimal to Strings rather than literal float or double, since those can get rounding errors (eg, 0.15 as a float might actually be 0.1499999999) whereas BigDecimal created from a String is exact.
Assuming you're happy to leave the logging of the final amount to the end, that gets us to something like :
static final BigDecimal BASICSALES = new BigDecimal("1.10");
static final BigDecimal IMPORTSALES = new BigDecimal("1.05");
static final BigDecimal BASICANDIMPORTSALES = new BigDecimal("1.15");
for(String orderLine : order) {
String[] splitOrder = orderLine.split("at\\ ");
String name = splitOrder[0];
BigDecimal value = new BigDecimal(splitOrder[1]));
BigDecimal taxRate;
if(isBasic(name)) {
if (isImport(name)) {
taxRate = BASICANDIMPORTSALES;
System.out.println("Both " + k);
} else {
taxRate = BASICSALES;
System.out.println("Basic " + k);
}
} else {
if (isImport(name)) {
taxRate = IMPORTSALES;
System.out.println("Import " + k);
} else {
taxRate = BigDecimal.ONE;
System.out.println("Neither " + k);
}
}
BigDecimal amountWithTax = amount.multiply(taxRate).round(new MathContext(4));
System.out.println(name + " tax: $" + amountWithTax);
newOrder.put(name, amountWithTax);
}
I am currently working on an assignment that requires me to create a "bottle class" for a pre-made "bottle demo" file my professor made. This is the description of the assignment:
Write a Bottle class. The class has these 14 methods: read(), set(int), >set(Bottle), get(), and(Bottle), subtract(Bottle), multiply(Bottle), >divide(Bottle), add(int), subtract(int), multiply(int), divide(int), >equals(Bottle), and toString(). The toString() method will be given in class. All >add, subtract, multiply, and divide methods return a Bottle. Your Bottle class >must guarantee bottles always have a positive value and never exceed a maximum >number chosen by you. These numbers are declared as constants of the class. Each >method wit ha parameter must be examined to determine if the upper or lower bound >could be violated. Consider each method carefully and test only the conditions >that could be violated.
And here is the demo code:
public static void main(String[] args) {
int x;
bottle bottle1 = new bottle();
bottle bottle2 = new bottle();
bottle bottle3 = new bottle();
bottle bottle4 = new bottle();
bottle bottle5 = new bottle();
System.out.println("please enter a number for bottle1:");
bottle1.read(); // affected my max and min
System.out.println("Bottle1 is this value " + bottle1 + ".");
System.out.println("Please enter a number for bottle2:");
bottle2.read(); // affected by max and min
bottle3.set(0);
bottle3 = bottle3.add(bottle1);
bottle3 = bottle3.add(bottle2);
bottle3 = bottle3.divide(2);
System.out.println("The 2 bottle average is: " + bottle3 + ".");
System.out.print("Subtracting bottle1 from bottle2 is: " );
bottle3 = bottle2.subtract(bottle1);
System.out.println( bottle3);
bottle3 = bottle2.divide(bottle1);
System.out.println("Dividing bottle2 with bottle1 is: " + bottle3 + ".");
if (bottle1.equals(bottle2))
{
System.out.println("Bottle1 and bottle2 are equal.");
}
else
{
System.out.println("Bottle1 and bottle2 are not equal.");
}
System.out.println("Bottle4 is now given the value of 10 with the set() method.");
bottle4.set(10);
System.out.println("The value of bottle4 is " + bottle4 + ".");
System.out.println("Bottle4 is now multiplied with bottle1. The value is placed in bottle5.");
bottle5 = bottle1.multiply(bottle4);
System.out.println("The value of bottle5 is " + bottle5 + ".");
System.out.println("Enter an integer to add to the value bottle1 has.");
System.out.println("The sum will be put in bottle3.");
Scanner keyboard = new Scanner(System.in);
x = keyboard.nextInt();
bottle3 = bottle1.add(x);
System.out.println("Adding your number " + x +
" to bottle1 gives a new Bottle with " + bottle3 + " in it.");
System.out.print("Adding the number " + bottle2 + " which is the number" +
" in bottle2 to the\nnumber in ");
bottle2 = bottle1.add(bottle2);
System.out.println("bottle1 which is " + bottle1 +" gives " + bottle2 + ".");
}
}
And this is the code I have made so far:
public class bottle {
Scanner scan = new Scanner(System.in);
private int value;
public void Bottle() {
value = 0;
}
public void read() {
value = scan.nextInt();
}
public void set(bottle) {
value = bottle1.value;
}
public void set(int bottle1) {
value = bottle1;
}
public bottle add(bottle) {
value = value + bottle1.value;
}
public bottle subtract(bottle) {
}
public bottle multiply(bottle) {
}
public bottle divide(bottle) {
}
public bottle add(int bottle) {
}
public bottle subtract(int bottle) {
}
public bottle multiply(int bottle) {
}
public bottle divide(int bottle) {
value = value / bottle;
}
public String toString() {
String name = null;
return name;
}
public boolean equals(bottle bottle) {
if (this == bottle) {
return true;
}
else {
return false;
}
}
}
What I need help on is how do I get my methods to work? ( add(int), divide(bottle), divide(int), etc)
And for there to be a max and min for values the user can input, I know that it can be placed at the top of the class code, but how do I make it so that every time the user inputs a number and the math outputs that the max and min will be checked every time to see if any number violates the set rule?
My I know my class code is missing many key components (I think return methods for the math parts) but I am struggling to stay sane trying to figure out what to do. Any help would be greatly appreciated and thanks in advance.
I will also answer any questions that you might have to the best of my ability.
EDIT: I have remade my code after reading the chapter about classes in my textbook and my knowledge is a bit better than before. Here is my new code:
Scanner scan = new Scanner(System.in);
private int value;
private int max = 100;
private int min = 0;
public bottle() {
// sets default value as zero
this.value = 0;
}
public void read() {
value = scan.nextInt();
}
public void set(int value) {
this.value = value;
}
public int add(bottle) {
if (this.value + bottle < this.max && this.value + bottle > this.min)
return this.value + bottle;
else
System.out.println("Please enter another number");
int x = scan.nextInt();
return add(x);
// the few lines above checks to see if the number violates the max and min
}
public int subtract(bottle) {
if (this.value - bottle < this.max && this.value - bottle > this.min)
return this.value - bottle;
else
System.out.println("Please enter another number");
int x = scan.nextInt();
return subtract(x);
}
// though there is this error under the word bottle in the parentheses
public int multiply(bottle) {
if (this.value * bottle < this.max && this.value * bottle > this.min)
return this.value * bottle;
else
System.out.println("Please enter another number");
int x = scan.nextInt();
return multiply(x);
}
public int divide(bottle) {
if (this.value / bottle < this.max && this.value / bottle > this.min)
return this.value / bottle;
else
System.out.println("Please enter another number");
int x = scan.nextInt();
return divide(x);
}
// the String toString method, format as shown by the professor.
public String toString()
{
return this.max + " " + this.min + " " + this.value;
Though I still have 4 errors in my class which is the word bottle inside the parentheses after my add, subtract, multiply, and divide method. Thus the demo file has 8 errors which are all the math methods. I am not sure what to do because "bottle" is an object right? Then how do I add 2 bottles together, or am I taking the wrong approach?
It looks like you're almost on the right track. These will help:
https://www.tutorialspoint.com/java/java_object_classes.htm
https://www.tutorialspoint.com/java/java_methods.htm
Pay attention to what an instance is and also how passing in arguments to methods works along with returning.
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.
I'm writing this program that will let you enter in an amount for each quarters, dimes, nickels and pennies and return their amount in $. After that, I want to be able to add up the dollar amounts they produce without having to enter in all of the coin amounts a second time. Any ideas? Thanks in advance.
import java.util.*;
public class HalfDollar {
public static final Scanner CONSOLE = new Scanner(System.in);
public static void main(String[] args) {
quarterDollarAmount( );
dimeDollarAmount( );
nickelDollarAmount( );
pennyDollarAmount( );
totalDollarAmount( );
}
public static double quarterDollarAmount( ) {
System.out.print("Enter the number of quarters: ");
int quarterDollar = CONSOLE.nextInt( );
double amount = quarterDollar * 0.25;
System.out.println(quarterDollar + " Quarter are $" + amount);
return amount;
}
public static double dimeDollarAmount( ) {
System.out.print("Enter the number of dimes: ");
int dimeDollar = CONSOLE.nextInt( );
double amount = dimeDollar * 0.10;
System.out.println(dimeDollar + " Dimes are $" + amount);
return amount;
}
public static double nickelDollarAmount( ) {
System.out.print("Enter the number of nickels: ");
int nickelDollar = CONSOLE.nextInt( );
double amount = nickelDollar * 0.05;
System.out.println(nickelDollar + " Nickels are $" + amount);
return amount;
}
public static double pennyDollarAmount( ) {
System.out.print("Enter the number of pennies: ");
int pennyDollar = CONSOLE.nextInt( );
double amount = pennyDollar * 0.01;
System.out.println(pennyDollar + " Pennies are $" + amount);
return amount;
}
public static double totalDollarAmount( ) {
double quarter = quarterDollarAmount();
double dime = dimeDollarAmount();
double nickel = nickelDollarAmount();
double penny = pennyDollarAmount();
double total = quarter + dime + nickel + penny;
System.out.println("Total amount is $" + total);
return total;
}
}
Hmmm, this smells to me like a homework problem. If you are truly the one who wrote this code, any number of solutions should be pretty obvious. But whatever, I won't judge your journey. Since you are returning the amount from each method, just keep a running total of all the amounts as you go along, then change your totalDollarAmount method to take the total as input instead of asking for it again:
double total = 0.0;
total += quarterDollarAmount( );
total += dimeDollarAmount( );
total += nickelDollarAmount( );
total += pennyDollarAmount( );
totalDollarAmount( total );
You're not doing anything with your variables. Just calling them and then they're moving out of scope.
You could either store the returned value in a global variable to use later.
private double quarter, dime, total;
public static void main(String[] args) {
quarter = quarterDollarAmount();
dime = dimeDollarAmount();
total = (quarter + dime);
s.o.p(total);
}
If you don't care about the value after printing it out you can either total them up with local variables or literally just total up your methods as follows.
public static void main(String[] args) {
s.o.p(quarterDollarAmount( ) + dimeDollarAmount( ) + ....);
}
To get your value to 2 decimal places use something like the following:
DecimalFormat format = new DecimalFormat("#.00");
Double total_formatted = Double.parseDouble(format.format(total));
s.o.p(total_formatted);
That enforces the value to have 2 decimal places with an optional amount of digits left of the decimal place.
Final thing, you probably don't want to make everything static. It basically defeats the point of object orientation as static variable will persist throughout all objects of a class.