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.
Related
I am working on an assignment "Dessert Shoppe" and basically what I need to do is to create DessertItem subclasses Candy, Cookie, IceCream, Sundae and Checkout. I am also provided with DessertItem class & DessertShoppe and I am not allowed to modify them.
While I have created all these subclasses, when I run it on my TestCheckout.java , it will not work but rather display getName() in Sundae cannot override getName() in DessertItem.
public final String getName(){
^
overriden method is final.
I will provide you guys all the classes that I have made now.
public class DessertShoppe {
public final static double TAX_RATE = 6.5; // 6.5%
public final static String STORE_NAME = "M & M Dessert Shoppe";
public final static int MAX_ITEM_NAME_SIZE = 25;
public final static int COST_WIDTH = 6;
public static String cents2dollarsAndCents(int cents) {
String s = "";
if (cents < 0) {
s += "-";
cents *= -1;
}
int dollars = cents/100;
cents = cents % 100;
if (dollars > 0)
s += dollars;
s +=".";
if (cents < 10)
s += "0";
s += cents;
return s;
}
}
public abstract class DessertItem {
protected String name;
public DessertItem() {
this("");
}
public DessertItem(String name) {
if (name.length() <= DessertShoppe.MAX_ITEM_NAME_SIZE)
this.name = name;
else
this.name = name.substring(0,DessertShoppe.MAX_ITEM_NAME_SIZE);
}
public final String getName() {
return name;
}
public abstract int getCost();
}
public class Cookie extends DessertItem{
protected double number;
protected double pricePerDoze;
public Cookie(String _n, double _ppd, int _number){
super(_n);
pricePerDoze = _ppd;
number = _number;
}
public int getCost(){
return (int)Math.round(number / 12 * pricePerDoze);
}
}
public class Candy extends DessertItem{
protected double weight;
protected double pricePerPound;
public Candy(String _n, double _ppp, int _w){
//using parent's constructor with name while storing its own properties
super(_n);
pricePerPound = _ppp;
weight = _w;
}
public int getCost(){
return (int)Math.round(weight * pricePerPound);
}
}
public class IceCream extends DessertItem{
protected int cost;
public IceCream(String _n, int _cost){
super(_n);
cost = _cost;
}
public int getCost(){
return cost;
}
}
public class Sundae extends IceCream{
protected String topName;
protected int topCost;
public Sundae(String _n0, int _cost0, String _n1, int _cost1){
//put the icecream name in icecream while putting top name and cost in a separate property
super(_n0, _cost0);
topName = _n1;
topCost = _cost1;
}
public final String getName(){
//return both the icecream name and the topping name
return name + " " + topName;
}
public int getCost(){
//return the sum of the icecream and the topping
return cost + topCost;
}
}
public class Checkout{
protected int size;
protected DessertItem[] dessertItems;
protected int amount;
protected int sum;
protected final double taxRate;
Checkout(){
size = 100;
dessertItems = new DessertItem[size];
amount = 0;
sum = 0;
taxRate = DessertShoppe.TAX_RATE;
}
public void enterItem(DessertItem d){
dessertItems[amount] = d;
amount ++;
}
public int numberOfItems(){
return amount;
}
public int totalCost(){
//make sum into zero, and calculate price from every item
sum = 0;
for(int i = 0; i < amount; i ++){
sum += dessertItems[i].getCost();
}
return sum;
}
public int totalTax(){
//use the totalCost method
return (int)(Math.round(this.totalCost() * taxRate / 100));
}
public void clear(){
//clear the array
for(DessertItem d : dessertItems){
d = null;
}
amount = 0;
sum = 0;
}
public String toString(){
String result = "Thank You! \n";
result += DessertShoppe.STORE_NAME + "\n";
result += "Purchased: ";
String totalPay = DessertShoppe.cents2dollarsAndCents( totalCost()+totalTax() );
if(totalPay.length() > DessertShoppe.COST_WIDTH){
totalPay = totalPay.substring(0, DessertShoppe.COST_WIDTH);
}
result += "$" + totalPay;
return result;
}
}
public class TestCheckout {
public static void main(String[] args) {
Checkout checkout = new Checkout();
checkout.enterItem(new Candy("Peanut Butter Fudge", 2.25, 399));
checkout.enterItem(new IceCream("Vanilla Ice Cream",105));
checkout.enterItem(new Sundae("Choc. Chip Ice Cream",145, "Hot Fudge", 50));
checkout.enterItem(new Cookie("Oatmeal Raisin Cookies", 4, 399));
System.out.println("\nNumber of items: " + checkout.numberOfItems() + "\n");
System.out.println("\nTotal cost: " + checkout.totalCost() + "\n");
System.out.println("\nTotal tax: " + checkout.totalTax() + "\n");
System.out.println("\nCost + Tax: " + (checkout.totalCost() + checkout.totalTax()) + "\n");
System.out.println(checkout);
checkout.clear();
checkout.enterItem(new IceCream("Strawberry Ice Cream",145));
checkout.enterItem(new Sundae("Vanilla Ice Cream",105, "Caramel", 50));
checkout.enterItem(new Candy("Gummy Worms", 1.33, 89));
checkout.enterItem(new Cookie("Chocolate Chip Cookies", 4, 399));
checkout.enterItem(new Candy("Salt Water Taffy", 1.5, 209));
checkout.enterItem(new Candy("Candy Corn",3.0, 109));
System.out.println("\nNumber of items: " + checkout.numberOfItems() + "\n");
System.out.println("\nTotal cost: " + checkout.totalCost() + "\n");
System.out.println("\nTotal tax: " + checkout.totalTax() + "\n");
System.out.println("\nCost + Tax: " + (checkout.totalCost() + checkout.totalTax()) + "\n");
System.out.println(checkout);
}
}
The expected output should be:
Number of items: 4
Total cost: 1331
Total tax: 87
Cost + Tax: 1418
M & M Dessert Shoppe
--------------------
2.25 lbs. # 3.99 /lb.
Peanut Butter Fudge 8.98
Vanilla Ice Cream 1.05
Hot Fudge Sundae with
Choc. Chip Ice Cream 1.95
4 # 3.99 /dz.
Oatmeal Raisin Cookies 1.33
Tax .87
Total Cost 14.18
Number of items: 6
When a method is marked as final, it means that it cannot be overridden in a subclass.
Therefore, you need to use the getName() method as it stands, and figure out how to get the appropriate value into the name variable.
Luckily, there's a constructor in IceCream that does that, so all you need to do is pass into the constructor what you want getName() to return (and what you want getCost() to return):
public Sundae(String _n0, int _cost0, String _n1, int _cost1){
super(_n1 + " Sundae with\n" + _n0, _cost0 + _cost1);
}
This way, your Sundae class doesn't need a getName() or a getCost() method.
As stated in other answers, the final modifier means that the method cannot be overridden by any of its subclasses.
There are two ways around this:
The first is to pass the arguments into the Sundae constructor as shown by Jason:
super(_n0 + " " + _n1, _cost0 + _cost1);
The second would be to utilize the fact that Sundae is a subclass of IceCream, which is a subclass of DessertItem. The name field is protected, meaning that you could directly access the field from the constructor.
Keep in mind, that with the second option, you will need to explicitly check to make sure that the name you provide is shorter than DessertShoppe.MAX_ITEM_NAME_SIZE to keep in line with that standard length.
The simpler and probably intended solution would be the first one, though both are valid.
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
I am trying to call my methods within main but after entering my dollars and cents, the values don't change when I print them
import java.text.DecimalFormat;
import java.util.Scanner;
public class ChangeMachine {
public static void main(String[] args) {
System.out.println("Change is good");
int dollars = 0;
int cents = 0;
int toonie = dollars/2;
int loonie = dollars%2;
int quarter = cents/25;
int dime = (cents%25)/10;
int nickel = ((cents%25)%10)/5;
ChangeMachine.getAmountFromUser(dollars, cents);
ChangeMachine.calculateCoins(dollars, cents);
ChangeMachine.displayInvoice(dollars, cents, toonie, loonie, quarter, dime, nickel);
}
Method to input the dollars and cents
Here I'm able to enter the amount but it won't appear when I try to display it
public static void getAmountFromUser(int dollars, int cents) {
Scanner input = new Scanner(System.in);
System.out.print("How many dollars? ");
dollars = input.nextInt();
System.out.print("How many cents? ");
cents = input.nextInt();
System.out.println();
input.close();
}
Method to calculate coins
public static void calculateCoins (int dollars, int cents){
DecimalFormat df = new DecimalFormat("#0.00");
double amount = dollars + cents/100.0;
System.out.println("$"+df.format(amount)+" requires:");
//-----Bonus-----
dollars=dollars+(cents+2)/100;
cents=(cents+2)%100;
//---------------
}
Method to display coins needed
public static void displayInvoice (int dollars, int cents, int toonie, int loonie, int quarter, int dime, int nickel){
System.out.println(toonie+" Toonies");
System.out.println(loonie+" Loonies");
System.out.println(quarter+" Quarters");
System.out.println(dime+" Dimes");
System.out.println(nickel+" Nickels");
}
}
... the values don't change when I print them
Yes, they shouldn't be changed because Java is a pass-by-value language. Any primitive variable, that is passed to a method, will not be changed (you are passing just a value of this variable, a new local variable will be created for the method).
How to solve that?
returning a changed value from a method
making operations over instance variables without local variable use
writing a custom class which keeps primitives
EDIT:
When we start talking about returning multiple values from a method, possibly, our methods are built not completely good (e.g. break the single responsibility principle). In that case, we need to refactor our methods. Consider methods with a single responsibility (calculateDollars, calculateCents, displayCoin). It will help to separate your code into small logical parts and make them more independent.
EDIT 2:
Now you are bound up with variables defined in the program's beginning. They, in their turn, are bound up with values of variables at that point. Take a look how you may correct that:
public int getLoonie(int dollars) {
return dollars % 2;
}
Better? Let's call it in the displayInvoice:
System.out.println(getLoonie(dollars) + " Loonies");
or much better
System.out.println(getLoonie(userCash.getDollars()) + " Loonies");
References to parameter arguments (local variables) in Java are pass-by-value, rather than pass-by-reference.
Each method has their own set of local variable references. When you re-assign a new value to a local variable reference, this change is local to that method.
Edit:
Here's one way to do it:
import java.text.DecimalFormat;
import java.util.Scanner;
public final class ChangeMachine {
private ChangeMachine() {
}
public static Cash getAmountFromUser() {
try(final Scanner input = new Scanner(System.in)) {
System.out.print("How many dollars? ");
final int dollars = input.nextInt();
System.out.print("How many cents? ");
final int cents = input.nextInt();
return new Cash(dollars, cents);
}
}
public static void calculateCoins(final Cash cash) {
final DecimalFormat decimalFormat = new DecimalFormat("#0.00");
final double amount = cash.getDollars() + cash.getCents() / 100.0D;
System.out.println("$" + decimalFormat.format(amount) + " requires:");
cash.setDollars(cash.getDollars() + (cash.getCents() + 2) / 100);
cash.setCents((cash.getCents() + 2) % 100);
}
public static void displayInvoice(final Cash cash) {
System.out.println(cash.calculateToonies() + " Toonies");
System.out.println(cash.calculateLoonies() + " Loonies");
System.out.println(cash.calculateQuarters() + " Quarters");
System.out.println(cash.calculateDimes() + " Dimes");
System.out.println(cash.calculateNickels() + " Nickels");
}
public static void main(final String[] args) {
final Cash cash = getAmountFromUser();
calculateCoins(cash);
displayInvoice(cash);
}
private static final class Cash {
private int cents;
private int dollars;
public Cash(final int dollars, final int cents) {
this.dollars = dollars;
this.cents = cents;
}
public int calculateDimes() {
return this.cents % 25 / 10;
}
public int calculateLoonies() {
return this.dollars % 2;
}
public int calculateNickels() {
return this.cents % 25 % 10 / 5;
}
public int calculateQuarters() {
return this.cents / 25;
}
public int calculateToonies() {
return this.dollars / 2;
}
public int getCents() {
return this.cents;
}
public int getDollars() {
return this.dollars;
}
public void setCents(final int cents) {
this.cents = cents;
}
public void setDollars(final int dollars) {
this.dollars = dollars;
}
}
}
Were you able to compile this code before? I was just checking the ChangeMachine, getAmountFromUser, and CalculateCoins methods to check them out in Notepad ++ and came up with several errors. The last two lines of code in getAmountFromUser , System.out.println(); and 'input.close();' don't seem to be necessary.
As for the other errors, I'm seeing a lot of class, interface, or enum expected errors.
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());
}
}
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.
I have my code running perfectly, except for my return value for the monthly loan calculator. It keeps on returning Infinity for both my monthly payments and total payments. Please help with the formula. This is a homework. All i need to know is if I am implementing the formula incorrectly. I get the feeling that it is somehow trying to divide over 0 and then returning infinity, but I could be wrong.
public class MyLoan
{
private double amountBorrowed;
private double yearlyRate;
private int years;
public double A;
public double n = years * 12;
public MyLoan(double amt, double rt, int yrs)
{
amountBorrowed = amt;
yearlyRate = rt;
years = yrs;
}
public double getAmountBorrowed()
{
return amountBorrowed;
}
public double getYearlyRate()
{
return yearlyRate;
}
public int getYears()
{
return years;
}
public double monthlyPayment()
{
double i = (yearlyRate / 100) / 12;
A = (amountBorrowed) * (i * Math.pow(1+i, n)) / (Math.pow(1+i, n) -1);
return A;
}
public double totalPayment()
{
return A * (years * 12);
}
public String toString()
{
return "Loan: " + "$" + amountBorrowed + " at " + yearlyRate + " for " + years + " years";
}
public static void main(String[] args)
{
final double RATE15 = 5.75;
final double RATE30 = 6.25;
StdOut.println("***** Welcome to the Loan analyzer! *****");
String ans = "Y";
do {
StdOut.print("\n Enter the principle amount to borrow: ");
double amount = StdIn.readDouble();
MyLoan fifteenYears = new MyLoan(amount, RATE15, 15);
MyLoan thirtyYears = new MyLoan(amount, RATE30, 30);
double amount15 = fifteenYears.monthlyPayment();
double total15 = fifteenYears.totalPayment();
double amount30 = thirtyYears.monthlyPayment();
double total30 = thirtyYears.totalPayment();
StdOut.println("===========ANALYSES==========");
StdOut.println(fifteenYears);
StdOut.println("Monthly payment = " + "$" + amount15);
StdOut.println("Total payment = " + "$" + total15);
StdOut.println("");
StdOut.println("");
StdOut.println(thirtyYears);
StdOut.println("Monthly payment = " + "$" + amount30);
StdOut.println("Total payment = " + "$" + total30);
StdOut.println("=============================");
StdOut.print("\n ** Do you want to continue (y/n)? ");
ans = StdIn.readString();
} while (ans.toUpperCase().equals("Y"));
StdOut.println("\n********** Thank you. Come again! **********");
}
}
You should be debugging this yourself, but I'll give you a hint. What is 1^n (where n is a positive integer)? Where, in your code, are you using this construct?
There is many ways to calculate interest and the most common is just
A = amountBorrowed * (yearlyRate / 100) / 12;