I am trying to create a method so that if the user enters a number of cents over 99, the updateMoney method will add dollars accordingly and then place the extra change once the cents goes under 100.
public void updateMoney(int cent) {
int addDollars = 0;
int change = 0;
if (cent > 99) {
for(int i = cent; i > 99; i -= 100)
{
addDollars += 1;
cent -= 100;
}
}
this.dollars = dollars + addDollars;
this.cents = cent;
}
public Money(int dol, int cent) {
if (cent < 0 || dol < 0) {
System.out.println("Invalid amount entered");
} else {
if (cent > 99) {
updateMoney(cent);
}
this.dollars = dol;
this.cents = cent;
}
}
This is the code I am currently working with.
I had originally tried a different method that ended up not working so I tried doing something like this instead but my outputs are still off.
In my driver I ran
Money money = new Money(15, 300); and the output was $15.00 when it should end up being $18.99
You should consider storing your dollars and cents in one long value. The following code takes your dollars and cents, combines them, adds the user's inputted cents correctly, and splits them up in dollars and cents again. But why not just keep them together all the time?
long dollarsWithCents = dollars * 100 + cents;
dollarsWithCents += parsedUserInput;
cents = dollarsWithCents % 100;
dollars = dollarsWithCents / 100;
Related
We would like to assess a service charge for cashing a check. Th service charge depends on the amount of the check. If the check amount is less than 10$, we will charge 1$. If the amount is greater than 10$ but less than 100$, we will charge 10% of the amount. If the amount is greater than 100$, but less than 1,000$, we will charge 5$ plus 5% of the amount. If the value is over 1,000$, we will charge 40$ plus 1% of the amount. Use a multibranch/nested if-else statement to compute for the service charge.
tried writing source code but failed.
I think it will look like this. I put the amount randomly.
int amount = 500;
double pay = 0;
if(amount > 1000){
pay = 40+(amount*0.01);
} else if(amount > 100 && amount < 1000){
pay = 5+(amount*0.05);
} else if(amount > 10 && amount < 100){
pay = amount*0.1;
} else if(amount < 10){
pay = 1;
}
System.out.println(pay+"$")
public double getCharge(int check_amount) {
if (check_amount < 10) {
return 1;
} else if (check_amount < 100) {
return 0.1 * check_amount;
} else if (check_amount < 1000) {
return 5 + 0.05 * check_amount;
} else if (check_amount > 1000) {
return 40 + 0.01 * check_amount;
}
return 0;
}
If we start with the lowest condition, we can neglect to have two conditions in the if statement.
In the main:
public static void main(String[] args) {
System.out.println(getCharge(9)) //when value is less than 10
System.out.println(getCharge(90)) //when value is less than 100
System.out.println(getCharge(900)) //when value is less than 1000
System.out.println(getCharge(5000)) //when value is greater than 1000
}
Output:
1
9
50
90
The question asks for nested if statements, so this code may fair better:
public double getCharge(int check_amount) {
if (check_amount < 1000){
if (check_amount < 100){
if (check_amount <10){
return 1;
}else {
return 0.1*check_amount;
}
} else {
return 5 + 0.05*check_amount;
}
} else {
return 40 + 0.01*check_amount;
}
}
This has the same function as the previous code i posted but as nested if-else statements as per request.
I'm trying to use the return value "average" in calcAverage method into the determineGrade method to get out a char value (A B C D F).
However, it repeats the loop when I code this way. Is there a way to just get the return value from the calcAverage and not have to execute the loop again and ask the same test scores?
package Chapter5;
import java.util.Scanner;
public class TestAverageAndGradewithLoop {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("How many tests?: ");
int test = input.nextInt();
System.out.print("Average test score is: " + calcAvergage(test) );
int mark = calcAvergage(test);
System.out.print("Letter grade is: " + determineGrade(mark) );
}
public static int calcAvergage(int test){
Scanner input = new Scanner (System.in);
int total = 0;
int x;
for (x = 1; x <= test; x++)
{
System.out.print("What is the score for test " + x + " : ");
int scores = input.nextInt();
total = total + scores;
}
int average = total/(x-1); //have to do -1 because the final increment value of x is stored as x+1
return average;
}
public static char determineGrade(int average)
{
char mark = 0;
if (average >= 90 && average <= 100)
{
mark = 'A';
}
else if (average >= 80 && average <= 89)
{
mark = 'B';
}
else if (average >= 70 && average <= 79)
{
mark = 'C';
}
else if (average >= 60 && average <= 69)
{
mark = 'D';
}
else if (average <= 60)
{
mark = 'F';
}
return mark;
}
}
Instead of this:
System.out.print("Average test score is: " + calcAvergage(test) );
int mark = calcAvergage(test);
Do this
int mark = calcAvergage(test);
System.out.print("Average test score is: " + mark );
There is no need to call the function twice when you are playing with the return value. Assign it to a variable and then use it.
Like this?
int mark = calcAvergage(test);
System.out.print("Average test score is: " + mark);
From my understanding you do not want to input a number then press enter then enter another number then press enter and so on...
If you say you have 3 test cases in console just type 3 space separated numbers like 10 12 3.
Your question is confusing and your code has logical errors, im sorry. You have if statements using the same logic.(example below) I would say learn up more on programming logic and you will answer your own question
else if (average >= 60 && average <= 69)
{
mark = 'D';
}
else if (average <= 60)
{
mark = 'F';
}
Thx to Avinash Raj for the pointer. I understand now.
the result of the calcAverage is stored in the variable mark, then I can use the int value from the result to both display what the score is as well as display and execute the determineGrade method.
I'm attempting to create a function that returns coins after an item has been purchased. I'm not finished, but the code below is an attempt to find the number of quarters, dimes, nickels and pennies that should be returned:
public String getChange(VendingMachine vendingMachine, Change change) {
double dispensedQuarters = 0;
double dispensedDimes = 0;
double dispensedNickels = 0;
double dispensedPennies = 0;
double d = Double.parseDouble(vendingMachine.getFunds());
if (d % .25 == 0) {
dispensedQuarters = d / .25;
} else if (d % .25 != 0) {
double remainder = d % .25;
d = d - remainder;
dispensedQuarters = d / .25;
if (remainder % .10 == 0) {
dispensedDimes = remainder / .10;
} else if (remainder % .05 == 0) {
dispensedNickels = remainder / .05;
} else if (remainder % .01 == 0) {
dispensedPennies = remainder / .01;
} else {
dispensedDimes = dispensedNickels = dispensedPennies = 0;
}
} else if (d % .10 == 0) {
dispensedDimes = d / .10;
} else if (d % .05 == 0) {
dispensedNickels = d / .10;
}
}
Is there a more compact way of creating a function that will find the number of quarters, dimes, nickels, and pennies that should be returned?
You could do this more elegantly by using enums.
Just create the different Coin objects using an enum, and add the value in the constructor. Make sure the enum instances are in descending order.
enum Coin {
QUARTER(25), DIME(10), NICKEL(5), PENNY(1);
private final int value;
private Coin(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
Then iterate over all different types of coins, and subtract as many coins from the change amount until the remaining value is smaller than the coin value.
private List<Coin> getCoins(int value) {
List<Coin> coins = new ArrayList<>();
// Loop over all different kind of coins, starting with the coin
// with the highest value
for (Coin coin : Coin.values()) {
// For each kind, subtract the coin value as many times as
// possible, then advance to the next coin.
while (value >= coin.getValue()) {
value -= coin.getValue();
coins.add(coin);
}
}
return coins;
}
Example code:
getCoins(95);
// returns a list with 3 quarters and 2 dimes.
The abovementioned code does indeed return the least number of coins — at least in this case. But note that it does not necessarily in all cases. There are cases where it's better to return more coins of a lower value, instead of ones of a higher value.
For example, if you have the coins TWELVY (value 12), DIME (value 10), NICKEL (value 5) and PENNY (value 1), and the change would be 45, the least number of coins would be 5 (4 dimes and 1 penny) instead of 8 (3 twelvies, 1 nickel and 4 pennies).
I see some issues with some of this code.
if (remainder % .10 == 0) {
This only tells you if you could pay the entire rest of your coins out in dimes - it does not tell you if you need a dime or two. For example, if remainder was 0.23 this condition would be false, even though you should be paying two dimes.
} else if (remainder % .05 == 0) {
Same issue. If you had 0.07 left to pay, this condition would be false, but it would still be appropriate to pay a nickel.
else if (remainder % .01 == 0) {
This check seems unneeded, and getting rid of it could make your code more compact. This will always be true, unless you have fractions of a penny for some reason. (This could be due to rounding errors, which, as was pointed out in the comments, could be avoided by using integers.)
Caution: calculateChange - takes number of cents as a parameter
public class QuarterDimeNickelPenny {
public static void main(String[] args) {
calculateChange(94); // Should be 3, 1, 1, 4
calculateChange(50); // Should be 2, 0, 0, 0
calculateChange(30); // Should be 1, 0, 1, 0
calculateChange(14); // Should be 0, 1, 0, 4
calculateChange(69); // Should be 2, 1, 1, 4
calculateChange(75); // Should be 3, 0, 0, 0
}
private static void calculateChange(int cents) {
int quarters = cents / 25;
int leftover = cents - quarters * 25;
int dimes = leftover / 10;
leftover = leftover - dimes * 10;
int nickels = leftover / 5;
leftover = leftover - nickels * 5;
int pennies = leftover;
System.out.println(quarters + ", " + dimes + ", " + nickels + ", " + pennies);
}
}
Try this, hope this helps
I am using arrays for a programming project due tonight. I am able to add up all the numbers of the array, but from there I am unable to remove the maximum and minimum values from it. My attempt and the actual project description is below...
In the sport of diving, seven judges award a score between 0 and 10, where each score may be a floating-point value. The highest and lowest scores are thrown out and the remaining scores are added together. The sum is then multiplied by the degree of difficulty for that dive. The degree of difficulty ranges from 1.2 to 3.8 points. The total is then multiplied by 0.6 to determine the diver’s score.
Write a computer program that inputs a degree of difficulty and seven judges’ scores and outputs the overall score for that dive. The program should ensure that all inputs are within the allowable data ranges.
package baker;
import java.util.Scanner;
public class DiveScoreDriver {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double total = 0;
double totalFinal = 0;
double divingScores[] = new double[7];
double input;
double difficultyInput = 0;
double minimum = divingScores[0];
double maximum = divingScores[0];
for (int i = 1; i < divingScores.length + 1; i++)
{
System.out.println("Judge " + i + " please enter your score.");
input = keyboard.nextDouble();
System.out.println();
if(input < 0 || input > 10)
{
System.out.println("Invalid Score");
return;
}
else
{
total += input;
}
}
while (difficultyInput < 1.2 || difficultyInput > 3.8)
{
System.out.println("Difficulty Rating: ");
difficultyInput = keyboard.nextDouble();
}
for(int i = 0; i < divingScores.length; i++)
{
if(divingScores[i] < minimum)
minimum = divingScores[i];
if(divingScores[i] > maximum)
maximum = divingScores[i];
}
total = total - maximum - minimum;
total = total * difficultyInput;
total = total * 0.6;
System.out.printf("\nThe overall score for the dive: %.1f\n", total);
}
}
The portion in particular that I am struggling with is here:
for(int i = 0; i < divingScores.length; i++)
{
if(divingScores[i] < minimum)
minimum = divingScores[i];
if(divingScores[i] > maximum)
maximum = divingScores[i];
}
total = total - maximum - minimum;
total = total * difficultyInput;
total = total * 0.6;
The code runs and produces a correct output, but it does not seem to subtract the max and min values and the problem requests... Thanks for the help!
You have forgotten to add each judge's score to the array divingScores. You can fix this by changing the first for loop to the following:
for (int i = 0; i < divingScores.length; i++)
{
System.out.println("Judge " + (i + 1) + " please enter your score.");
input = keyboard.nextDouble();
System.out.println();
if(input < 0 || input > 10)
{
System.out.println("Invalid Score");
return;
}
else
{
total += input;
divingScores[i] = input;
}
}
You should also initialize minimum as:
minimum = 0
If you do not, every score above 0 will not be considered for the minimum.
You never set the array values in the else branch within your for loop, it should look like this:
if(input < 0 || input > 10) {
System.out.println("Invalid Score");
return;
} else {
divingScores[i] = input;
total += input;
}
Before the second loop, you can use Java 8 functional programming to get the minimum and maximum like this, which is shorter:
double minimum = Arrays.stream(divingScores).min().getAsDouble();
double maximum = Arrays.stream(divingScores).max().getAsDouble();
Alternatively, you should initialize the minimum and maximum values properly, one way to do this in general for at least one element in the array is:
double minimum = Double.MAX_VALUE; // Use your maximum in your case
double maximum = Double.MIN_VALUE; // Use your minimum in your case
You can sort the array and then add the array elements except first and last element of sorted array which will automatically remove the minimum and maximum
Arrays.sort(divingScores);
double ans=0;
for(int i=1;i<divingScores.length-1;i++){
System.out.println(divingScores[i]);
ans+=divingScores[i];
}
I am working on a project that calculates the number of coins used to produce a certain total of change. For some reason, my output is only reading this:
Quarters:
Dimes:
end.
It doesn't print the integer being calculated, and does not continue past dimes. I have tried using different loops and print statements, but am at a loss. Any insight of hints would be greatly appreciated.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minimumcoinsproject;
import java.util.Scanner;
/**
*
* #author user
*/
public class MinimumCoinsProject {
/**
*
* #author
*/
static public class MinumimCoinsProject//a class is not an object, but a blueprint for an object. It is the building blocks.
{
}
public static void main(String[] args) {
// TODO code application logic here
{ //initialization
int change = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
Scanner in;
in = new Scanner(System.in);
System.out.println("Lets calclulate the minimum coins.\n");
System.out.println("PLease enter amount of change.(1-99)\n");
change=in.nextInt(); //asks for the amount of change to calculate
//start of while loop
while ( change >= 25)
{
quarters = quarters+1;
change = quarters - 25;
System.out.printf("Quarters:\n", quarters);
}
if (10 >= change)
{
dimes = dimes + 1;
change = change - 10;
System.out.printf("Dimes: \n", dimes);
}
if (change >=5)
{
nickels = nickels + 1;
change = change - 5;
System.out.printf("Nickles: \n",nickels);
}
if ( change == 0)
System.out.printf("Pennies: \n", change);
}
}
}
First while loop :
change = quarters - 25;
should be
change = change - 25;
Then the three if loops should also be while loops.
I think this should work:
int change = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
Scanner in;
in = new Scanner(System.in);
System.out.println("Lets calclulate the minimum coins.\n");
System.out.println("PLease enter amount of change.(1-99)\n");
change=in.nextInt(); //asks for the amount of change to calculate
//start of while loop
while ( change >= 25)
{
quarters = quarters+1;
change = change - 25;
}
System.out.printf("Quarters:\n"+quarters+"\n");
while (change>=10)
{
dimes = dimes + 1;
change = change - 10;
}
System.out.printf("Dimes: \n"+dimes+"\n");
while(change>=5)
{
nickels = nickels + 1;
change = change - 5;
}
System.out.printf("Nickles: \n"+nickels+"\n");
if ( change>0)
System.out.printf("Pennies: \n"+change+"\n");
Change:
System.out.printf("Quarters:\n", quarters);
To this:
System.out.printf("Quarters:%d\n", quarters);
Do the same for dimes, nickels, pennies.
I looked further and found some more issues with your code.
This should get it working:
while (change >= 25) {
quarters = quarters + 1;
change = change - 25;
}
if (quarters > 0) {
System.out.printf("Quarters:%d\n", quarters);
}
if (change >= 10) {
dimes = dimes + 1;
change = change - 10;
System.out.printf("Dimes:%d\n", dimes);
}
if (change >= 5) {
nickels = nickels + 1;
change = change - 5;
System.out.printf("Nickles:%d\n", nickels);
}
if (change > 0) {
System.out.printf("Pennies:%d\n", change);
}