Extracting the value of variables from objects? - java

I am working on a Java programming assignment, where objects have just been introduced to the class.
I need to write a method that accepts an object of type Money, that has attributes of dollars and cents. It needs to extract the dollars and cents so that they can be added to another object of type Money.
Would I be correct to say that I need to write a support method whose purpose is to extract the dollars and cents variables from the Money object?
I'm thinking that perhaps I need to convert the Money object to a String so that I can extract and manipulate the dollars and cents. Would this be correct?
I'm really confused as to how to approach this. Also I don't want anyone just giving me the answer, as I wont learn anything.
Any advice is greatly appreciated! :)
EDIT:
I have been given the following class:
package project6; // Test program for the Money class
public class Project6 {
public static void main(String[] args) {
test setMoney and toString
testSet ();
testAdd ();
testSubtract();
testEquals();
testLessThan();
}
private static void testSet () {
System.out.println ("Testing set and toString");
Money myMoney = new Money();
myMoney.setMoney(5, 75);
System.out.println (myMoney.toString()); // $5.75
myMoney.setMoney(75, 5);
System.out.println (myMoney.toString()); // $75.05
myMoney.setMoney(0, 5);
System.out.println (myMoney.toString()); // $0.05
myMoney.setMoney (-1, 5);
System.out.println (myMoney.toString()); // $0.00
myMoney.setMoney (1, -5);
System.out.println (myMoney.toString()); // $0.00
}
private static void testAdd () {
System.out.println ("Testing add");
Money total = new Money();
Money temp = new Money();
total.setMoney (0, 0);
for (int value = 1; value < 100; value += 15) {
temp.setMoney (1, value);
System.out.print(total + " + " + temp + " = ");
total.add(temp);
System.out.println (total.toString());
}
}
private static void testSubtract () {
System.out.println ("Testing subtract");
Money total = new Money();
Money temp = new Money();
total.setMoney (10, 10);
for (int value = 1; value < 100; value += 15) {
temp.setMoney (1, value);
System.out.print(total + " - " + temp + " = ");
total.subtract(temp);
System.out.println (total.toString());
}
}
private static void testEquals () {
System.out.println ("Testing equals");
Money wallet1 = new Money();
Money wallet2 = new Money();
wallet1.setMoney(7, 7);
wallet2.setMoney(7, 7);
System.out.println (wallet1 + " = " + wallet2 + " is " +
wallet1.equals(wallet2));
System.out.println (wallet1 + " = " + wallet2 + " is " +
wallet2.equals(wallet1));
wallet2.setMoney(7, 17);
System.out.println (wallet1 + " = " + wallet2 + " is " +
wallet1.equals(wallet2));
wallet2.setMoney(17, 1);
System.out.println (wallet1 + " = " + wallet2 + " is " +
wallet1.equals(wallet2));
}
private static void testLessThan () {
System.out.println ("Testing lessThan");
Money wallet1 = new Money();
Money wallet2 = new Money();
wallet1.setMoney(7, 7);
wallet2.setMoney(7, 7);
System.out.println (wallet1 + " < " + wallet2 + " is " +
wallet1.lessThan(wallet2));
wallet2.setMoney(17, 7);
System.out.println (wallet1 + " < " + wallet2 + " is " +
wallet1.lessThan(wallet2));
wallet2.setMoney(5, 7);
System.out.println (wallet1 + " < " + wallet2 + " is " +
wallet1.lessThan(wallet2));
wallet2.setMoney(7, 20);
System.out.println (wallet1 + " < " + wallet2 + " is " +
wallet1.lessThan(wallet2));
wallet2.setMoney(7, 4);
System.out.println (wallet1 + " < " + wallet2 + " is " +
wallet1.lessThan(wallet2));
}
}
/*
* Expected output
*
Testing set and toString
$5.75
$75.05
$0.05
$0.00
$0.00
*/
I need to write the Money class, with the following instance methods:
setMoney(int dollarsIn, int centsIn) –Set the dollars and cents to the values of the parameters. If either input is negative, set the dollars and cents to 0.
add(Money moneyIn) – add the dollars and cents of the parameter to the current object. If the cents exceeds 100, adjust the dollars and cents accordingly.
subtract(Money moneyIn) – subtract the parameter from the current object If the cents fall below 0, then the dollars and cents must be adjusted. If the number of dollars falls below 0, then set both the dollars and cents to 0
boolean equals(Money moneyIn): return true if both the dollars and cents of the parameter match the dollars and cents of the current object, otherwise return false
boolean lessThan(Money moneyIn): return true if the current object represents less money than the parameter. otherwise return false
String toString(): return the values of the object as a String formatted as $dd.cc
I figured I would start with the setMoney and toString methods and see whether I can instantiate a Money object and return the objects attributes. So in my Project6 class I have commented out all of the methods except for the setMoney() and toString() methods.
Here is what I have come up with so far.
package project6;
public class Money {
private int dollars;
private int cents;
public void setMoney(int dollarsIn, int centsIn){
dollars = dollarsIn;
cents = centsIn;
}
public int getDollars(){
return dollars;
}
public int getCents(){
return cents;
}
public void add(Money moneyIn){
dollars = dollars + moneyIn.getDollars();
cents = cents + moneyIn.getCents();
dollars = dollars + (cents - (cents%100))/100; // roll over cents into dollars if greater than 100
}
public String toString(Money moneyIn){
return "$" + moneyIn.getDollars() + "." + moneyIn.getCents();
}
}
When I just try to run the testSet() method from the Project6 class, I get the following output:
Testing set and toString
project6.Money#7885a30c
project6.Money#7885a30c
project6.Money#7885a30c
project6.Money#7885a30c
project6.Money#7885a30c
instead of the following expected output:
Testing set and toString
$5.75
$75.05
$0.05
$0.00
$0.00
EDIT2 - So in the setMoney() method call, I need to return the money object? This perhaps could explain my unexpected output?
EDIT 3 - ok, I have advanced a bit, I am successfully setting and getting dollars and cents.
I modified the Project6 class to confirm that I am correctly setting and getting the dollars and cents variables, like so:
System.out.println ("Testing set and toString");
Money myMoney = new Money();
myMoney.setMoney(5, 75);
System.out.println("Dollars = " + myMoney.getDollars());
System.out.println("Cents = " + myMoney.getCents());
Now when I run the program it outputs
Dollars = 5
Cents = 75
According to the instructions I have been given, I need to write a method called toString(), however such a method is native in Java (from what I have worked out).
So I think I have to pass a String to the toString() method which I have preformatted to $dd.cc
EDIT 4 - The toString() method when called is in the following format:
myMoney.setMoney (1, -5);
System.out.println (myMoney.toString()); // $0.00
I think I just figured it out! I don't pass the object as a parameter! I simply call the getDollars() and getCents() methods!
I had previously thought that I could only call those methods with respect an object, but it seems that is done during the method call!
Yay! Happy dance!!
EDIT 6:
When I call the following method from the Project6 class:
private static void testAdd () {
System.out.println ("Testing add");
Money total = new Money();
Money temp = new Money();
total.setMoney (0, 0);
for (int value = 1; value < 100; value += 15) {
temp.setMoney (1, value);
System.out.println("TOTAL = " + total);
System.out.println("TEMP = " + temp);
System.out.print(total + " + " + temp + " = ");
total.add(temp);
System.out.println (total.toString());
}
}
It enters the for loop and prints out the values of total and temp, then adds them.
The second time through the loop, it prints the value of total, but not temp, and does not add them.
For all subsequent iterations through the loop it does not print the values of either total or temp.
I have been stepping through it line by line with the debugger, but I am totally stumped as to why this is happening.
Can anyone offer any suggestions as to what I am missing/doing wrong?
Here is my current code for the Money class:
package project6;
public class Money {
private int dollars;
private int cents;
public Money(){
}
public void setMoney(int dollarsIn, int centsIn){
dollars = dollarsIn;
cents = centsIn;
if (dollars < 0 || cents < 0){
dollars = 0;
cents = 0;
}
}
private int getDollars(){
return dollars;
}
private int getCents(){
return cents;
}
public void add(Money moneyIn){
dollars = dollars + moneyIn.getDollars();
cents = cents + moneyIn.getCents();
if (cents >= 100){
dollars = dollars + (cents - (cents%100))/100; // roll over cents into dollars if greater than 100
cents = (cents%100);
moneyIn.setMoney(dollars, cents);
}
}
public void subtract(Money moneyIn){
dollars = dollars - moneyIn.getDollars();
cents = cents - moneyIn.getCents();
if (cents < 0){
dollars = dollars + (cents + (cents%100)) / 100;
cents = 100 + cents;
}
if (dollars < 0){
dollars = 0;
cents = 0;
}
}
public boolean equals(Money moneyIn){
dollars = moneyIn.getDollars();
cents = moneyIn.getCents();
Money newMoney = new Money();
return (moneyIn.equals(newMoney));
}
public String toString(){
String output = "";
dollars = getDollars();
cents = getCents();
if (cents < 10)
output = "$" + dollars + ".0" + cents;
return output;
}
}

Yes, you would have to add a few basic methods to your Money class.
This is how I would do it:
The Money constructor accepts two arguments, one for dollars and one for cents
The dollars and cents would be properties of the class (no need to put the value in a String and have to work with it)
Add getters and setters for the dollars and cents
Override the equals() method to compare with other Money objects by dolars/cents
Implement an add(Money) method in which you pass another Money object and add its value (dollars/cents) to the current object
Edited:
To handle cases where the constructor receives more than 100 cents, we would do:
this.cents = cents%100;
this.dollars = dollars + ((cents-this.cents) / 100);
That should be all you need.

I'm thinking that perhaps I need to convert the Money object to a String so that I can extract and manipulate the dollars and cents. Would this be correct?
This seems too complicated of a solution for something simple, your other idea seems better. You probably want to do something with "getter" and "setter" methods. I'm sure you've learned about those, if not they are methods meant to get and set the private fields of an object.
Hope this helps!

You can create two getter function on money class for dollar and cents...
In your present class use these method as per your requirements.
Last thing you can override toString() in money class for debugging and printing for information..
I hope this might help you

I'm thinking that perhaps I need to convert the Money object to a String so that I can extract and manipulate the dollars and cents. Would this be correct?
You do not need conversion to String. Adding is a behaviour which belongs to Money itself. You could write a method add(Money m), which adds the amounts and gives you a new Money-Object with the result back.
public Money add(Money m){
//Do the adding here
}

To expand in the previous answer, in Java a class usually has its fields defined as private objects with public getter and setter methods for each field.
In your case the money object most likely has the methods getDollars() and getCents()
So your method takes a money object as its parameter
public double addMoney(Money obj) {
....
}
Inside the method you can simply call the getter methods for dollars and cents to get their values
public double addMoney(Money obj) {
int dollars = obj.getDollars();
double cents = obj.getCents();
....
}
If you have a running count of the money in your class with getter and setter methods it would look like this
public double addMoney(Money obj) {
int dollars = obj.getDollars();
double cents = obj.getCents();
this.setTotalDollars(this.getTotalDollars() + dollars);
this.setTotalCents(this.getTotalCents() + cents);
return this.getTotalDollars() + this.getTotalCents();
}
To add to another object just use the getDollars() and getCents() method on each and add them together
Strings should not be used anywhere unless that is the required return type

Okay, pay close attention to this, the logic for your setMoney Method is wrong to get the expected output, your method has to look like this.
public void setMoney (int dollarsln, int centsln){
if( centsln > 0 && dollarsln > 0 || centsln >= 0 && dollarsln >= 0){
dollars = dollarsln;
cents = centsln;
}
else{
dollars = 0;
cents = 0;
}
}

I finally found the problem!
In my toString() method I had set up an output string for when the cents < 10, but I failed to put in a case for when they were >=10.
Fixed that & now it works as expected!
This has been an excellent learning experience, thank you all for helping me, it is greatly appreciated!

You can do Like this provided dollars and cents are the variables of the money class
public Money addToNewMoney(Money money) {
Money newMoney = new Money();
newMoney.setDollars(money.getDollars());
newMoney.setDollars(money.getCents());
return newMoney;
}
Later perform other operations using new Money object.
May be this will Help
Thanks

As I received quality pointers from multiple people here, I think it is difficult to credit a single person with helping me solve this problem.
What is the protocol for such a situation?
The final code I successfully used for this was:
/*
* This Money class is for use with Project6 class.
* It provides public methods as follows:
* setMoney(int dollarsIn, centsIn) sets a Money objects attributes
* add(Money moneyIn) adds the dollars & cents of the parameter to the current object
* subtract(Money moneyIn) subtracts the parameter from the current object
* boolean equals(Money moneyIn) returns true if both dollars and cents of the parameter matches those of the current object, otherwise false
* boolean lessThan(Money moneyIn) return true if the current object represents less money than the parameter, otherwise false
* String toString() returns the values of the object formatted as $dd.cc
*
* It provides private methods as follows:
* int getDollars() returns dollar value of the current object
* int getCents() returns cents value of the current object
*
*/
package project6;
/**
* #author Ross Satchell
* #version 1.0
*/
public class Money {
private int dollars; /** variable to hold dollar value of object*/
private int cents; /** variable to hold cents value of object*/
public Money(){ /** constructor for object of type Money */
}
/** Set the Money object's attributes. If dollarsIn or centsIn are
* less than zero, it sets both dollars and cents to zero
* #param dollarsIn
* #param centsIn
*/
public void setMoney(int dollarsIn, int centsIn){
dollars = dollarsIn;
cents = centsIn;
if (dollars < 0 || cents < 0){
dollars = 0;
cents = 0;
}
}
/** Gets dollar attribute from Money object
* #return dollars
*/
private int getDollars(){
return dollars;
}
/** Gets cents attribute from object of type Money
* #return cents
*/
private int getCents(){
return cents;
}
/**
* Adds two Money objects together
* #param moneyIn
*/
public void add(Money moneyIn){
dollars = this.getDollars() + moneyIn.getDollars();
cents = this.getCents() + moneyIn.getCents();
if (cents >= 100){
dollars = dollars + (cents - (cents%100))/100; // roll over cents into dollars if greater than 100
cents = (cents%100);
this.setMoney(dollars, cents);
}
}
/**
* Subtracts a Money object from another Money object.
* If result is less than zero, this method sets both
* dollars and cents to zero
*
* #param moneyIn
*/
public void subtract(Money moneyIn){
dollars = dollars - moneyIn.getDollars();
cents = cents - moneyIn.getCents();
if (cents < 0){ // roll over cents if less than zero
dollars -= (cents/100) + 1;
cents = 100 + cents;
}
if (dollars < 0){
dollars = 0;
cents = 0;
}
}
/**
* Determines whether 2 money objects attributes are equal
* #param moneyIn
* #return boolean
*/
public boolean equals(Money moneyIn){
return (this.getCents() == moneyIn.getCents() && this.getDollars() == moneyIn.getDollars());
}
/**
* Determines whether the monetary attributes of an Money object are less than those of another Money object
* #param moneyIn
* #return boolean
*/
public boolean lessThan(Money moneyIn){
return (this.getDollars() * 100 + this.getCents()) < (moneyIn.getDollars() * 100 + moneyIn.getCents());
}
/**
* Converts Money objects attributes to a String
* #return String
*/
public String toString(){
String output;
if (getCents() < 10)
output = "$" + this.getDollars() + ".0" + this.getCents();
else output = "$" + this.getDollars() + "." + this.getCents();
return output;
}
}

package test;
public class BankAccount
{
private Money balance;
public BankAccount()
{
// start with zero balance
balance = new Money(0,0);
}
public void addMoneyToBalance(Money m)
{
balance.setDollars(m.getDollars());
balance.setCents(m.getCents());
}
public String accountBalanceToString()
{
return "$" + balance.getDollars() + "." + balance.getCents();
}
// inner class defines how money is held in memory
private static class Money
{
private int dollars;
private int cents;
public Money()
{}
// overloaded constructor, for a one-shot setup
public Money(int newDollars, int newCents)
{
dollars = newDollars;
cents = newCents;
}
public void setDollars(int newDollars)
{
dollars = newDollars;
}
public void setCents(int newCents)
{
cents = newCents;
}
public int getDollars()
{
return dollars;
}
public int getCents()
{
return cents;
}
}
public static void main(String[] args)
{
BankAccount myAccount = new BankAccount();
// prepare a deposit of $69.69
Money currentDeposit = new Money(69, 69);
myAccount.addMoneyToBalance(currentDeposit);
System.out.println(myAccount.accountBalanceToString());
}
}

Related

Combining Two Objects (java)

New to java and I'm confused as to how I can combine these two objects. Sorry if I am not clear / if this has been asked before.
I need to add one.PiggyBank to two.PiggyBank
We are not allowed to change the program used to output the code
public class PiggyBank {
doubles pennies, nickels, dimes, quarters, totalValue, bankTotal;
public PiggyBank(int p, int n, int d, int q)
{
pennies = p;
nickels = n;
dimes = d;
quarters = q;
totalValue = pennies + nickels + dimes + quarters;
}
public void addPenny()
{
}
//accessors
public double getP()
{
return pennies;
}
public double getN()
{
return nickels;
}
public double getD()
{
return dimes;
}
public double getQ()
{
return quarters;
}
public double combinePiggy(double bank2)
{
two.
bankTotal = bank1 + bank2;
}
public static void main(String[] args) {
PiggyBank one = new PiggyBank(5, 5, 5, 5);
PiggyBank two = new PiggyBank(2, 3, 4, 1);
System.out.println(“Account 1: “ + one + “\n”);
System.out.println(“Account 2: “ + two + “\n”);
one.combinePiggy(two);
System.out.println(“Account 1: “ + one + “\n”);
System.out.println(“Account 2: “ + two + “\n”);
}
}
You need to create that combinePiggy(PiggyBank) method and then add the values of the parameter to the corresponding values you call this on.
Somewhat abstract and simplified example to get you started (you should do the real thing yourself to have a learning effect):
class Thing {
int x;
int y;
void combine(Thing otherThing) {
x += otherThing.x;
y += otherThing.y;
}
}
There is so much wrong with this. First of all, it does not make sense to have those attributes listed as type double.
For example: pennies = 0.5; this makes no sense, as you cannot have half a penny in a piggy bank. This needs to be adjusted for all accessor and mutator methods.
public class PiggyBank {
int pennies, nickels, dimes, quarters;
double bankTotal;
.
.
.
public int getP()
{
return pennies;
}
public int getN()
{
return nickels;
}
public int getD()
{
return dimes;
}
public int getQ()
{
return quarters;
}
}
Additionally, the combinePiggy method should not have a return type, as you are not returning anything. Furthermore, as the main method suggests, the combinePiggy method should have another piggybank as a parameter. The method should then add the number of each piggy bank together, as well as the total of each bank.
public void combinePiggy(PiggyBank bank2)
{
pennies += bank2.pennies;
nickels += bank2.nickels;
dimes += bank2.dimes;
quarters += bank2.quarters;
bankTotal += bank2.bankTotal;
}
Another thing, judging by the main method, your class needs a toString method. A toString method is exactly what the name implies. It converts an object into a string. (I'll leave it for you to write the appropriate toString to fit your main method)
public String toString(){
return "This piggy bank has " + pennies + " pennies, " + nickels + " nickels, " +
dimes + " dimes, " + quarters + " quarters.";
}
Also, you cannot just add the number of coins in order to get a bank total. Example: You have a penny, a nickel, a dime and a quarter. 0.01+0.05+0.10+0.25=0.41. The way you are doing it, you're bank total would just add up the number of coins.
public PiggyBank(int p, int n, int d, int q)
{
pennies = p;
nickels = n;
dimes = d;
quarters = q;
bankTotal = pennies*0.01 + nickels*0.05 + dimes*0.1 + quarters*0.25;
}
I think I've done more than answer your question. I will leave the addPenny as well as the setter methods to you. It seems you are very new to Java. I suggest you watch a few videos and read some documentation about the language before you tackle this assignment. Here is a video that more or less sums up the language.

Java. counting the correct change

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.

Assistance on making a class for a pre-made demo file

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.

Method calculations/arguments in Java

I have to create a virtual coffee shop where the user enters their order number, how many of that order they want, calculate the subtotal and the discount, etc. The whole point of this is that the process's divided into various methods. Most of the methods are pretty simple, but I'm having trouble with the computeSubTotal method. I have to initialize subtotal in the main method to make this work, but when the subtotal's calculated in computeSubTotal, it always ends up being zero. Sorry if this seems stupid, but I have no idea what I'm doing wrong, help?
import java.util.Scanner;
public class CoffeeShopWithMethods
{
public static void main(String[] args)
{
Scanner user_input = new Scanner (System.in);
String user_name;
System.out.print("\nPlease enter your name: ");
user_name = user_input.next();
System.out.println("\nWelcome to the Java Byte Code Coffee Shop, " + user_name + "!");
int orderNumber = 0;
int orderQuan = 0;
double subTotal = 0.0;
//Beginning of calls to methods
displayMenu();
getItemNumber(orderNumber);
getQuantity(orderQuan);
computeSubTotal(orderNumber, orderQuan, subTotal);
discountCheck(subTotal);
}
public static void displayMenu()
{
System.out.println("\nHere is our menu: \n" + "\n 1. Coffee $1.50" + "\n 2. Latte $3.50" + "\n 3. Cappuccino $3.25" + "\n 4. Espresso $2.00");
}
public static int getItemNumber(int orderNumber) //prompts user for item number (1 for coffee, 2 for latte, etc...)
{
Scanner user_input = new Scanner(System.in);
System.out.print("\nPlease enter the item number: ");
orderNumber = user_input.nextInt();
final double Coffee = 1.50;
final double Latte = 3.50;
final double Cappuccino = 3.25;
final double Espresso = 2.00;
double Cost = 0;
if (orderNumber == 1)
Cost = Coffee;
if (orderNumber == 2)
Cost = Latte;
if (orderNumber == 3)
Cost = Cappuccino;
if (orderNumber == 4)
Cost = Espresso;
return orderNumber;
}
public static int getQuantity(int orderQuan)
{
Scanner user_input = new Scanner(System.in);
System.out.print("\nPlease enter the quantity: ");
orderQuan = user_input.nextInt();
return orderQuan;
}
public static double computeSubTotal(int orderNumber, int orderQuan, double subTotal)
{
subTotal = (orderNumber * orderQuan);
System.out.print("Your total before discount and tax is: $" + subTotal);
return subTotal;
}
public static boolean discountCheck(double subTotal) //takes subtotal and returns true if user earned a discount (over $10)
{
if (subTotal >= 10.00)
return true;
else
return false;
}
}
Your methods getItemNumber, getQuantity, computeSubTotal and discountCheck all return a value, but you are not storing that return value in your main method.
In addition to that, your getItemNumber() method is only storing the cost locally, which is then discarded when the method is finished - the cost should be returned (and the method probably renamed).
You probably should have something like this:
//Beginning of calls to methods
displayMenu();
double itemCost = getItemCost(); // was getItemNumber()
orderQuan = getQuantity(orderQuan);
subTotal = computeSubTotal(itemCost, orderQuan);
boolean shouldDiscount = discountCheck(subTotal);
Of course, to use an object-oriented approach, the variables should be members of your class, then you wouldn't need to pass or return values - they would be accessible to all methods in the class.
public static double computeSubTotal(int orderNumber, int orderQuan, double subTotal)
{
subTotal = (orderNumber * orderQuan);
System.out.print("Your total before discount and tax is: $" + subTotal);
return subTotal;
}
In your computeSubTotal method, you do
subTotal = (orderNumber * orderQuan);
This is not going to intiailize the variable in the main method; you are re-initializing the parameter variable.
In your main method, you should be doing
subTotal = computeSubTotal(orderNum, orderQuan);
instead of calling the method without using the return value. You might have noticed that I didn't pass subTotal to the method. This is not needed. You can instead re-declare the variable inside the method:
public static double computeSubTotal(int orderNumber, int orderQuan)
{
double subTotal = (orderNumber * orderQuan);
System.out.print("Your total before discount and tax is: $" + subTotal);
return subTotal;
}
This applies to the other variables aswell. Java is pass-by-value, so if you pass a value to a method, a new reference is created for the method (when you do int varName in your method's parameters when you declare the method)

Why do I have to enter in data twice?

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.

Categories