I am student, trying to finish a homework lab. Right now I am struggling to use the input from JOptionPane to display the results based on the input. There are two files to my lab, the CoinCounterTester.java and the CoinCounter.java. Both compile but it should print the total numbers of dollars and the total number of cents (teachers instructions) "Output should be in the console window, and should demonstrate the use of and escape sequences". I'm not sure if any part of the tester is correct but I think the JOptionPane methods are correct. I also think I'm supposed to parse them to get them into integer form , however I do not know how to print the designated number of dollars and number of cents left over based on user input. Can anyone explain?
Thanks
Edit:
Ok the answer seems like its correct but I'm confused about using the constructor call. What would you put for the parameters for the constructor call, I put
CoinCounter coinCounter = new CoinCounter(int quarters, int dimes, int nickels, int pennies);
but got seven errors
Edit 2:
I have now not included the variable type as well wisely suggested and input
CoinCounter coinCounter = new CoinCounter(quarters, dimes, nickels, pennies);
but I still get 4 errors (error cannot find symbol) :(. Can anyone suggest a correction please?
Edit 3: Added the println statements and moved the constructor call to the bottom but whenever I run the program I cannot get the file to print the number of dollars and the number of cents?!
import javax.swing.JOptionPane;
/**
* A class to test the CoinCounter class
*/
public class CoinCounterTester
{
/**
* Tests methods of the CoinCounter class
* #param args not used
*/
public static void main(String[] args)
{
String quarter = JOptionPane.showInputDialog("Enter the quantity of quarters");
int quarters = Integer.parseInt(quarter);
String dime = JOptionPane.showInputDialog("Enter the quantity of dimes");
int dimes = Integer.parseInt(dime);
String nickel = JOptionPane.showInputDialog("Enter the quantity of nickels");
int nickels = Integer.parseInt(nickel);
String penny = JOptionPane.showInputDialog("Enter the quantity of pennies");
int pennies = Integer.parseInt(penny);
CoinCounter coinCounter = new CoinCounter(quarters, dimes, nickels, pennies);
System.out.println(coinCounter.getDollars());
System.out.println(coinCounter.getCents());
System.exit(0);
}
}
/**
* A CoinCounter has a specific number of cents. It can provide the number of dollars and the
* number of cents that it contains
*/
public class CoinCounter
{
// constants
//*** These are class constants so they need public static
public static final int QUARTER_VALUE = 25;
public static final int DIME_VALUE = 10;
public static final int NICKEL_VALUE = 5;
public static final int PENNY_VALUE = 1;
public static final int PENNY_PER_DOLLAR_VALUE = 100;
// instance field (one - holds the total number of cents EX: 8,534)
private int total;
/**
* Constructs a CoinCounter object with a specified number of pennies,
* nickels, dimes and quarters
* #param quarterAmount the amount of quarters
* #param dimeAmount the amount of dimes
* #param nickelAmount the amount of nickels
* #param pennyAmount the amount of pennies
*/
public CoinCounter(int quarters, int dimes, int nickels, int pennies)
{
total = quarters * QUARTER_VALUE + nickels * NICKEL_VALUE + dimes * DIME_VALUE + pennies;
}
// add remaining methods as described
/**
* getDollars returns the number of dollars in the CoinCounter
* #return the number of dollars
*/
public int getDollars()
{
int dollars = (int) total / PENNY_PER_DOLLAR_VALUE;
return dollars;
}
/**
* getCents returns the number the numbers of cents left over after the dollars are removed
* #return the number of cents left over
*/
public int getCents()
{
int cents = total % PENNY_PER_DOLLAR_VALUE;
return cents;
}
}
What you're looking for is a constructor call. You have all the values. You just need to create a CoinCounter to count them for you. An example of doing that would look like:
CoinCounter coinCounter = new CoinCounter(1, 2, 3, 4);
After you have your CoinCounter, you can call methods on it, like coinCounter.getCents(). You print things out using System.out.println(<whatever you want to print>). Those should be the three things you need to finish up.
Edit: Close! Look carefully at how you called the constructor and how I did it. What you did is like this:
CoinCounter coinCounter = new CoinCounter(int 1, int 2, int 3, int 4);
Compare it to my example above.
You only put the variable type there when you define the constructor, not when you call it.
Related
For my cash register simulation, I have to take the change due and print it out in terms of 100s, 50s, 20s, 10s, 5s, 1s, and ofcourse change. I have two questions that I'm struggling with:
1.) Is there an easier way to figure out how many dollar bills are needed for each one if any? My equations work but it' s long and I think there's an easier way to do it?
2.) When dealing with cents is am i supposed to do (changeDue%100)?
changeDue is equal to 39.12 and I'm trying to pull of just the 12 cents, but I dont quite know how? Can someone please help explain to me?
double changeDue = 39.12;
double coins;
double change;
int hundreds;
int fifties;
int twenties;
int tens;
int fives;
int ones;
int quarters;
int dimes;
int nickels;
int pennies;
double cents;
//calculations for amount of each dollar bill that needs to be given back
hundreds = (int)(changeDue/100);
change = changeDue - (hundreds * 100);
fifties = (int)(change/50);
change = changeDue - (hundreds * 100) - (fifties * 50);
twenties = (int)(change/20);
change = changeDue - (hundreds * 100) - (fifties * 50) - (twenties * 20);
tens = (int)(change/10);
change = changeDue - (hundreds * 100) - (fifties * 50) - (twenties * 20) - (tens * 10);
fives = (int)(change/5);
change = changeDue - (hundreds * 100) - (fifties * 50) - (twenties * 20) - (tens * 10) - ( fives * 5);
ones = (int)(change/1);
//calculations for amount of coins that needs to be given back
cents = changeDue%100;
quarters = (int)cents/10;
The modulus operator gives the remainder after division. In your example changeDue % 100 divides the number by 100 and returns the remainder. If you provide the number in pennies, say 3912, then this will work exactly as you expect. However, you are using dollars instead. So first convert the dollar amount to pennies by multiplying by 100.
Note
ones = (int)(change/1); can be simplified to ones = (int) change;.
Another method to derive change less than a dollar is:
cents=changeDue-(int)changeDue
1.) Is there an easier way to figure out how many dollar bills are needed for each one if any? My equations work but it' s long and I think there's an easier way to do it?
I have found an easier way for your calculations. Refer to the code and code comments below.
public static void main(String args[]) {
double changeDue = 39.12; // The change needed
double change = changeDue; // Used for the calculations of change
/*
* Add here possible change, use an array so that you won't have to declare many
* variables This way if you want to add other possible changes you just have to
* add it in the array But make sure the possible changes is arrange in
* descending order
*/
double[] possibleChange = new double[] { 100, 50, 20, 10, 5, 1, 0.25, 0.10, 0.05, 0.01 }; // the possible changes
String[] possibleChangeLabel = new String[] { "Hundreds", "Fifties", "Twenties", "Tens", "Fives", "Ones", "Quarters", "Dimes", "Nickels", "Pennies" }; // used for printing
int[] coins = new int[possibleChange.length]; // Used for the number of coins needed for each possible change
/*
* Loop through all the possible changes and acquire the possible number of
* coins needed for each change
*/
for (int i = 0; i < possibleChange.length; i++) {
coins[i] = (int) (change / possibleChange[i]); // calculate the possible number of coins in the given change
change = (double) Math.round((change - (coins[i] * possibleChange[i])) * 100) / 100; // Update the change and limit to 2 decimal places
}
/*
* This is for printing
*/
System.out.println("Your change is $" + changeDue);
System.out.println("The change is composed of: ");
for (int i = 0; i < possibleChange.length; i++) {
if (coins[i] > 0) {
System.out.println( "\t" + coins[i] + " piece/s of $" + possibleChange[i] + "(" + possibleChangeLabel[i] + ")");
}
}
}
2.) When dealing with cents is am i supposed to do (changeDue%100)? changeDue is equal to 39.12 and I'm trying to pull of just the 12 cents, but I dont quite know how? Can someone please help explain to me?
I don't know why you are needing this process, but you can try my code below.
double number = 123.45; // Your change
int decimal = (int) number; // You will get the whole number part (123)
double fractional = number - decimal; // You will get the fraction part (45)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have been away from Java for awhile and am trying to recall and learn a lot still. I have a current project which is a piggy bank that you add coins to and can get various outputs. I am currently tasked with 5 methods plus a helper method for the constructors. I know what I want to do, but can't think through the code to get it done. I want to use the helper method to get the amounts for the other two constructors, but cannot get my head around it, I can only look through my book so long. Any input is appreciated.
The description for each method is as follows:
P.S. The code I do have may not be correct.
publicChangeJar() Default constructor that sets all the instance variables to zero
publicChangeJar(int quarters, int dimes, int nickels, int pennies) A constructor that initializes the instance variables with the provided values converted to quarters, dimes, nickels, and pennies.
public ChangeJar(final double amount) A constructor that initializes the instance variables with the provided value converted to quarters, dimes, nickels, and pennies. For example, if amount was 1.34 then you would have 5 quarters, 1 nickel, 4 pennies
public ChangeJar(final String amount)A constructor that accepts a string as a parameter with the provided value converted to appropriate number of quarters, dimes, nickels, and pennies. For example, if amount was “1.34” then you would have 5 quarters, 1 nickel, 4 pennies.
public ChangeJar(final ChangeJar other)A constructor that initializesthe instance variables of “this” ChangeJar object with the other object.
public class ChangeJar {
private int pennies;
private int nickels;
private int dimes;
private int quarters;
static boolean globalLock = false;
public ChangeJar(){
this(0,0,0,0);
}
public ChangeJar(int pennies, int nickels, int dimes, int quarters)throws IllegalArgumentException {
if (pennies < 0 || nickels < 0 || dimes < 0 || quarters < 0)
throw new IllegalArgumentException("You cannot have negative coins in the jar");
else this.pennies = this.pennies + pennies;
this.nickels = this.nickels + nickels;
this.dimes = this.dimes + dimes;
this.quarters = this.quarters + quarters;
}
public ChangeJar(double amount){
}
public ChangeJar(final String amount){
}
private double amountHelper(double amount){
amount = pennies*.01 + nickels*.05 + dimes*.10 + quarters*0.25;
return amount;
}
public ChangeJar(final ChangeJar other){
}
}
EDIT: My problem here is how to write the helper method to work in both constructors.
Constructor ChangeJar(double)
For your constructor with an amount, you want to use the maximum number of quarters, then the maximum number of pennies, and so on.
Let's say I have $2.87.
First, I will take 11 quarters. We still have $0.12 left.
Then, I will take 1 dime. We still have $0.02 left.
Then, I will take 0 nickel. We still have $0.02 left.
Then, I will take 2 pennies. We're done.
How to implement that? Let's say the amount is 2.87.
public ChangeJar(double amount) {
// How many quarters?
int quarters = (int) (amount / .25); // The division gives 9.48 and we cast the result to int so we get 9
amount = amount - quarters * .25;
System.out.println(quarters + " quarters. Remains: " + amount);
// How many dimes?
int dimes = (int) (amount / .10);
amount = amount - dimes * .10;
System.out.println(dimes + " dimes. Remains: " + amount);
// How many nickels?
int nickels = (int) (amount / .05);
amount = amount - nickels * .05;
System.out.println(nickels + " nickels. Remains: " + amount);
// How many pennies?
int pennies = (int) (amount / .01);
amount = amount - pennies * .01;
System.out.println(pennies + " pennies. Remains: " + amount);
// Prints:
// 11 quarters. Remains: 0.1200000000000001
// 1 dimes. Remains: 0.0200000000000001
// 0 nickels. Remains: 0.0200000000000001
// 2 pennies. Remains: 1.0061396160665481E-16
// Now we just set this in our properties:
this.quarters = quartes;
this.dimes = dimes;
this.nickels = nickels;
this.pennies = pennies;
}
As you can see, the problem is that the remainders are strange values. The constructor works but it's not really cool. Why? Because Java approximates the doubles.
I would suggest to work with ints. For example, you could change your unit from $ to $/100. Our same example with integer values (the input is not 2.87 but 287):
public ChangeJar(int amount) {
// How many quarters?
int quarters = amount / 25;
amount = amount - quarters * 25;
System.out.println(quarters + " quarters. Remains: " + amount);
// How many dimes?
int dimes = amount / 10;
amount = amount - dimes * 10;
System.out.println(dimes + " dimes. Remains: " + amount);
// How many nickels?
int nickels = amount / 5;
amount = amount - nickels * 5;
System.out.println(nickels + " nickels. Remains: " + amount);
// How many pennies?
int pennies = amount;
amount = amount - pennies;
System.out.println(pennies + " pennies. Remains: " + amount);
// Prints:
// 11 quarters. Remains: 12
// 1 dimes. Remains: 2
// 0 nickels. Remains: 2
// 2 pennies. Remains: 0
// Now we just set this in our properties:
this.quarters = quartes;
this.dimes = dimes;
this.nickels = nickels;
this.pennies = pennies;
}
That's already better!
But there is a lot of copy/paste in my code...
How could we make it better?
We can see that for each coin, I get the number of coins and then I subtract the value from the amount.
int amount = 287;
int[] values = new int[]{25, 20, 5, 1}; // The values of my coins
int[] results = new int[values.length];
for (int i = 0; i < values.length; i++) {
int valueOfCoin = values[i];
int numberOfCoins = amount / valueOfCoin; // Division gives the integer part of the result
results[i] = numberOfCoins;
amount = amount % valueOfCoin; // Modulo gives the remainder part of the result
// Or you could simply write: amount %= valueOfCoin;
}
System.out.println("RESULTS=" + Arrays.toString(results));
// Prints:
// RESULTS=[9, 1, 0, 2]
Constructor ChangeJar(String)
I suppose that the String is an amount so we will just convert the String to a Double and call the other constructor (ChangeJar(double)).
public ChangeJar(String amount) {
this(Double.valueOf(amount)); // Double.valueOf() will try to convert the String => Double
}
Constructor ChangeJar(ChangeJar)
The idea is just to copy the values of the other ChangeJar:
public ChangeJar(ChangeJar other) {
this(other.quarters, other.dimes, other.nickels, other.pennies);
}
I'm trying to write a program that will allow the user to create "loan" objects and measure the total amount that they have to pay after putting it through an interest equation. I'm having two problems with it that i've been messing with for a few hours but can't figure out for some reason. The biggest problem is that the class that is supposed to calculate the total payment of the loan after plugging in variables, but it ALWAYS returns zero and I can't figure out why. Is it a problem with syntax? I created a test loan class to test out the program that creates ten random loans with ten random time lengths and both the "totalPay" and the "monthlyPay" (which is dependent on totalPay) is always zero.
The second problem is that I was trying to sort the ten random loans based on the numberOfYears of the loan, but I can't get it to work! I tried a few methods for sorting and the one I included is the most recent and probably the one that's the dumbest hahaha but it's the one that I was playing with most recently. I've included all the code below, any ideas?
Loan class:
(it's a little long but the important thing is just the main loan class, totalPayment, and monthlyPayment )
public class Loan {
double annualInterestRate = 2.5;
int numberOfYears = 1;
double loanAmount = 1000;
double base;
double exponent;
double totalPay;
String summary;
double monthly;
String[] list = new String[10];
String s;
/**
* creates default loan with 2.5 annual interest rate 1 year and 1000$
*/
public Loan(){
}
/**
* totalPay = amount(1+rate/12)^(year*12)
*
* #param anualInterestRate
* #param numberOfYears
* #param loanAmount
*/
public Loan(double anualInterestRate, int numberOfYears, double loanAmount){
base = (double) ( loanAmount * (1+anualInterestRate/12));
exponent = (double) (numberOfYears * 12);
totalPay = (double) Math.pow(base, exponent);
}
/**
*
* #return total payment
*/
public double totalPayment(){
return this.totalPay;
}
/**
*
* #return Monthly Payment
*/
public double monthlyPayment(){
monthly = (totalPay/12);
return monthly;
}
}
TestLoan:
import java.util.Random;
public class TestLoan {
public static void main (String[] args){
Random r = new Random();
Loan[] list = new Loan[10];
for (int i = 0; i < 10; i++){
Loan x = new Loan();
list[i] = x;
System.out.println(list[i].toString());
}
System.out.println();
System.out.println();
for (int i = 0; i < 9; i++){
list[i].setNumberOfYears(r.nextInt(30));
if (list[i].getNumberOfYears() > list[i+1].getNumberOfYears())
list[i] = list[i+1];
System.out.println(list[i].toString());
}
}
}
Thank you for looking!
Edit got rid of the irrelevant code
You set the number of years, but you never calculate the base, exponent or totalPay. That only happens in a constructor you never call.
What you need to do is move functional code out of the constructor and into a calculation method. That constructor should be for constructing the object.
old constructor:
public Loan(double anualInterestRate, int numberOfYears, double loanAmount) {
base = (double) (loanAmount * (1 + anualInterestRate / 12));
exponent = (double) (numberOfYears * 12);
totalPay = (double) Math.pow(base, exponent);
}
better way:
public Loan(double annualInterestRate, int numberOfYears, double loanAmount) {
this.annualInterestRate = annualInterestRate;
this.numberOfYears = numberOfYears;
this.loanAmount = loanAmount;
}
public void calculatePay() {
base = (double) (loanAmount * (1 + annualInterestRate / 12));
exponent = (double) (numberOfYears * 12);
totalPay = (double) Math.pow(base, exponent);
}
Also, your method for sorting is flawed. You should decide what a good natural ordering for Loan is, then implement the Comparable interface.
Then you could use an existing sort library like this:
for (int i = 0; i < 9; i++) {
list[i].setNumberOfYears(r.nextInt(30));
list[i].calculatePay();
}
Arrays.sort(list);
for (Loan loan: list) {
System.out.println(loan);
}
I'm a beginner to java. When I ran the class & tester, there were no errors, but I'm not getting the output I want from the tester. I can't find what I'm doing wrong. Please help
Here's my code:
/**
* A CoinCounter has a specific number of cents. It can provide the number of dollars and the
* number of cents that it contains
*/
public class CoinCounter
{
// constants
public static final int PENNIES_PER_NICKEL = 5;
public static final int PENNIES_PER_DIME = 10;
public static final int PENNIES_PER_QUARTER = 25;
public static final int PENNIES_PER_DOLLAR = 100;
// instance field (one - holds the total number of cents EX: 8,534)
private int totalCents;
/**
* Constructs a CoinCounter object with a specified number of pennies, nickels, dimes and quarters
* #param pennies number of pennies
* #param nickels number of nickels
* #param dimes number of dimes
* #param quarters numbr of quarters
*/
public CoinCounter(int pennies, int nickels, int dimes, int quarters)
/**
* Computes the total value in pennies
*/
{
int totalCents = pennies + nickels * PENNIES_PER_NICKEL + dimes * PENNIES_PER_DIME + quarters * PENNIES_PER_QUARTER;
}
// ACCESSOR methods as described (only two)
/**
* Gets the number of dollars
* #return number of dollars
*/
public int getDollars()
{
int dollars = totalCents / PENNIES_PER_DOLLAR;
return dollars;
}
/**
* Gets the number of cents
* #return number of cents
*/
public int getCents()
{
int cents = totalCents % PENNIES_PER_DOLLAR;
return cents;
}
//MUTATOR METHODS - NONE FOR THIS PROGRAM
Here's my tester:
import javax.swing.JOptionPane;
/**
* A class to test the CoinCounter class
*/
public class CoinCounterTester
{
/**
* Tests methods of the CoinCounter class
* #param args not used
*/
public static void main(String[] args)
{
// Use JOptionPane to read in coins
String input = JOptionPane.showInputDialog("Please enter the number of pennies: ");
int pennies = Integer.parseInt(input);
input = JOptionPane.showInputDialog("Please enter the number of nickels: ");
int nickels = Integer.parseInt(input);
input = JOptionPane.showInputDialog("Please enter the number of dimes: ");
int dimes = Integer.parseInt(input);
input = JOptionPane.showInputDialog("Please enter the number of quarters: ");
int quarters = Integer.parseInt(input);
// Construct an object
CoinCounter myCoins = new CoinCounter(22, 8, 17, 5);
//Call the TWO ACCESSOR METHODS-print dollars & cents
System.out.println("The total dollars is: " + myCoins.getDollars());
System.out.println("The total cents is: " + myCoins.getCents());
System.exit(0);
//NO MUTATOR METHODS to test
}
}
After I run the tester and enter the amount of each coin, my output is
The total dollars is: 0
The total cents is: 0
instead of
The total dollars is: 3
The total cents is: 57
What am I doing wrong? Thanks!
change
int totalCents = pennies + nickels * PENNIES_PER_NICKEL....
to
this.totalCents = pennies + nickels....
"public static int readInt(String s)" wat does this exactly do in a program?? Currently i need to use 4 of these but they all different and for the one i showed up here, i need to make a program where the user is prompted something and if the input is an int then it gets displayed and then goes to the second input for the user and if right then goes, but else if not an int; if its a double then print out "This is not valid..." and then will repeat the first one again and will also do the same thing for the second input if the second one prompted by the user is not an integer. There will be a total of two inputs for the user. What should i do to make a program for this? I am confused of how to use this "public static int readInt(String s)".
package rationalnumber;
import java.util.*;
public class Utility
{
public static int readInt(String s)
{
}
public static double readDouble(String s)
/**
* Generates a random integer between min and max, inclusive
* Precondition: min <= max
* #param min lower bound for the random integer
* #param max upper bound for the random integer
* #return A random integer
*/
public static int randomInt(int min, int max)
{
}
/**
* Computes the gcd between 2 nonnegative integers
* Precondition: num1 >= 0, num2 >= 0
* #param num1 The first integer
* #param num2 The second integer
* #return the gcd of num1 and num 2, gcd is 1 if both are 0,
* gcd is the non-zero number if only one is 0.
*/
public static int gcd(int num1, int num2)
{
}
this is like part of the code....i also need to add comments on here well so far those are the last two parts of my code but i couldnt start it without the first two parts.
package rationalnumber;
/**
* Test program for the Utility class
*/
public class UtilityTest
{
public static void main(String[] args)
{
String prompt1 = "Enter first integer: ";
String prompt2 = "Enter second integer: ";
int a = Utility.readInt(prompt1);
int b = Utility.readInt(prompt2);
int small = Math.min(a, b);
int large = Math.max(a, b);
System.out.println("A few random integers: ");
System.out.println(Utility.randomInt(small, large));
System.out.println(Utility.randomInt(small, large));
System.out.println(Utility.randomInt(small, large));
System.out.println(Utility.randomInt(small, large));
System.out.printf("The gcd of %d and %d is ", a, b);
System.out.println(Utility.gcd(Math.abs(a), Math.abs(b)));
}
}
in the end i use this which is in the same program but in another folder to run it.
Break it down:
Public -- Signifies this is a public method
int -- Signifies that the function will return an integer
readInt -- Name of the function
String s -- Signifies that the function takes a parameter of type String that will be referred to as s within the function.
Public --a public method
int -- return tpye integer
readInt -- Name of the function that will read a string and return it as an integer.in your program it will read prompt1 and prompt2 , like take input form the user , and store them int a and int b.
String s -- Signifies that the function takes a parameter of type String that will be referred to as s within the function.