Create a Change application that prompts the user for an amount less than $1.00 and then displays the minimum number of coins necessary to make the change.
The change can be made up of quarters, dimes, nickels, and pennies.
Here is what I did:
public static void main(String[] args) {
System.out.println("Enter the amount in cents: ");
int a = in.nextInt();
if(a <= 100){
}else{
System.out.println("Try Again");
System.exit(0);
}
{
int q = (a/25);
int d = (a/25);
System.out.println("Quarters: " + q);
System.out.println("Dimes: " + d);
}
}
}
D is irrelevant. because I don't know how to get the remainder of quarters and divide it by 10 and so on all the way through pennies
To find the remainder of anything, subtract off the amount you've taken.
For free, you need to subtract off the coin price times the amounts as you go.
if(a <= 100){
int q = a/25;
a = a-q*25;
int d = a/10;
a = a-d*10;
}
Related
I am still pretty new to learning java and for an assignment I was given a set of data to run with my code.
After inputting some of the data, this exception appeared
I can't figure out why an exception is being thrown after I prompt user for money tended by the customer. Help is appreciated. Here is my code below:
public class cashRegister
{
public static void main(String[] args)
{
//represents the sale amount
double saleAmt;
//represents amount of money given by customer
double cusTend;
//represents customer's change
double cusChange = 0;
//Collects sale amount from user
Scanner customerIn = new Scanner(System.in);
System.out.println("Please enter the sale amount");
saleAmt = customerIn.nextDouble();
//Collects amount tended
System.out.println("Please enter amount tended by the customer");
cusTend = customerIn.nextDouble();
//Outputs customer's total change
cusChange = cusTend - saleAmt;
System.out.printf("Total Change: %.2f", cusChange,"\n");
//Splits change into Dollars and Cents
DecimalFormat decimalFormat = new DecimalFormat();
String moneyString = decimalFormat.format(cusChange);
String[] parts = moneyString.split("\\.");
String part2 = parts[1]; //ArrayIndexOutOfBoundException here
String dollars= parts[0];
double cents5 = Double.parseDouble(part2);
//Divides change by amount
int cents = (int)cents5;
int quarters = cents / 25;
int cents1 = cents % 25;
int dimes = cents1 / 10;
int cents2 = cents % 10;
int nickels = cents2 / 5;
int cents3 = cents % 5;
int pennies = cents3;
//Out prints the amount of dollars, quarters, dimes, nickles, and pennies
System.out.printf("\n"+ "Dollars :"+ dollars + "\n" );
System.out.printf("Quarters :" + quarters + "\n");
System.out.printf("Dimes :"+ dimes +"\n");
System.out.printf("Nickles :" + nickels +"\n");
System.out.printf("Pennies :" + pennies + "\n");
}
}
When sale amount is 92 and amount tended is 95, the total change is 3.
Hence moneyString is 3 and not 3.00
Therefore moneyString.split("\\.") will return an array that contains a single element only and that's why you are getting ArrayIndexOutOfBoundException.
You just need to check the number of elements in parts and add code that handles different numbers of elements.
Also, as mentioned in the comments, it is better to use class java.math.BigDecimal for money amounts (rather than double).
Refer to this SO question (and answer): How to display a number with always 2 decimal points using BigDecimal?
Note that there is also Java Money.
It is recommended to adhere to Java naming conventions which means that then name of your class should be CashRegister (and not cashRegister).
Remember that Java code is case-sensitive.
Here is my rewrite of your code. I check the number of elements in parts and handle the case where that number is zero or one or two.
Refer to the javadoc for method printf, I think you should change the code that calls that method. I have done so in the below code.
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Scanner;
public class CashRegister {
public static void main(String[] args) {
//Collects sale amount from user
Scanner customerIn = new Scanner(System.in);
System.out.println("Please enter the sale amount");
double tmp = customerIn.nextDouble();
//represents the sale amount
BigDecimal saleAmt = new BigDecimal(tmp);
//Collects amount tended
System.out.println("Please enter amount tended by the customer");
tmp = customerIn.nextDouble();
//represents amount of money given by customer
BigDecimal cusTend = new BigDecimal(tmp);
//Outputs customer's total change
BigDecimal cusChange = cusTend.subtract(saleAmt);
cusChange.setScale(2, RoundingMode.HALF_UP);
//Splits change into Dollars and Cents
String moneyString = String.format("%.2f", cusChange.doubleValue());
System.out.printf("Total Change: %s%n", moneyString);
String[] parts = moneyString.split("\\.");
String dollars;
if (parts.length > 0) {
dollars = parts[0];
}
else {
dollars = "0";
}
String part2;
if (parts.length > 1) {
part2 = parts[1];
}
else {
part2 = "0";
}
double cents5 = Double.parseDouble(part2);
//Divides change by amount
int cents = (int)cents5;
int quarters = cents / 25;
int cents1 = cents % 25;
int dimes = cents1 / 10;
int cents2 = cents % 10;
int nickels = cents2 / 5;
int cents3 = cents % 5;
int pennies = cents3;
//Out prints the amount of dollars, quarters, dimes, nickles, and pennies
System.out.printf("%nDollars : %s%n", dollars);
System.out.printf("Quarters: %d%n", quarters);
System.out.printf("Dimes : %d%n", dimes);
System.out.printf("Nickles : %d%n", nickels);
System.out.printf("Pennies : %d%n", pennies);
}
}
Here is a sample run of the above code:
Please enter the sale amount
92.00
Please enter amount tended by the customer
95.00
Total Change: 3.00
Dollars : 3
Quarters: 0
Dimes : 0
Nickles : 0
Pennies : 0
package gradeAvg;
import java.util.Scanner;
//Grade Average calculater
public class GradeAvg {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("Please Enter the first grade being added to the average:");
double average = input.nextInt();
System.out.print("The average is now: " + average + " Please enter the second grade being averaged:");
average += input.nextInt() ;
System.out.print("The average is now: " + average + " Please enter the third grade being averaged:");
average += input.nextInt() / 2;
System.out.print("The average is now: " + average + " Please enter the fourth grade being averaged:");
average += input.nextInt() / 2;
System.out.print("The average is now: " + average + " Please enter the fifth grade being averaged:");
average += input.nextInt() / 2;
input.close();
System.out.print(average);
}
}
Hey guys, I'm really new to java, and pretty terrible at math, I'm supposed to be making a program that allows the user to input a value, have it averaged out, print it out, and then allow the input of another value, have it averaged, and print, and continue. Am i going wrong when I divide by 2 at the end of each input or what?
Average is the sum of all the numbers divided by the number of numbers in the sum.
What you are doing here is not average. You are adding the half of every new number to the total sum. I don't what you are doing here.
Just to make things more understandable, let's make a sum and a counter:
public class GradeAvg {
public static void main(String[] args) {
int sum;
int counter;
// ...
}
}
Each time you ask for a number, you increment the counter and add the new number to sum:
int newNumber;
// ask for input
newNumber = input.nextInt()
sum += newNumber;
counter++;
You can then output the average like this:
System.out.println("The average is: " + (double)sum / counter);
That's wrong. each number you add weight 50% against the other numbers.
you need to keep track of the count (number of elements) and the sum and each time divide the sum by the number of elements.
so each time you add a number the function should be:
(OLD_AVERAGE*OLD_COUNT+NEW_NUMBER)/(OLD_COUNT+1)
or just use SUM and COUNT and each time AVERAGE=SUM/COUNT.
inc. count by 1 every new number.
inc sum by the number entered.
complete working solution... hope it helps...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
int count = 1;
double average = 0;
System.out.print("Please Enter the " + count + " grade being added to the average:");
for (; count <= 5;) {
sum = sum + input.nextInt();
average = sum / count;
System.out.println("The average is now: " + average);
count++;
if (count <= 5)
System.out.println("Please enter the " + count + " grade being averaged:");
}
input.close();
}
Can not for the life of me figure out why my average is not displaying correctly I've looked at it for like 2 hours.
import java.util.Scanner;
public class midterm
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int examScore =0;
int averageExamScore = 0;
int numStudent=0;
int sum=0;
while(examScore >= 0)
{
System.out.println("Enter exam scores (enter negative number to quit): ");
examScore = keyboard.nextInt();
numStudent++;
sum = sum + examScore;
}
if(numStudent > 0)
{
averageExamScore = sum/numStudent;
}
else
{
System.out.println("No scores to average");
}
}
}
The issue here is integer division.
averageExamScore = sum/numStudent;
All three of these arguments are integers, which means:
If you cast a part of your quotient to double, you'd lose precision (and fail compilation)
Example:
averageExamScore = (double)sum/numStudent; // wouldn't compile
The floor of the quotient sum/numStudent is provided instead of the whole number (so for a number like 4.9 you'd get 4).
You can fix this in a few ways:
Declare averageExamScore to be a double. This is required.
Either cast sum or numStudent to a double, or change their type to double.
You have defined averageExamScore as an integer, so integer arithmetic will be applied.
e.g.
5 / 2 == 2
1 / 2 == 0
Make averageExamScore into a double, and also cast your other integers to doubles.
Edit
To print out
do
if(numStudent > 0)
{
averageExamScore = sum/numStudent;
System.out.println ("average score is " + averageExamScore );
}
Go through the following code,
public class MidTerm {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int examScore = 0;
double averageExamScore = 0;
int numStudent = 0;
int sum = 0;
while (true) {
System.out.print("Enter exam scores (enter negative number to quit): ");
examScore = keyboard.nextInt();
if (examScore >= 0) {
numStudent++;
sum += examScore;
} else break;
}
if (numStudent > 0) {
averageExamScore = sum / numStudent;
System.out.println("Avarage score is : " + averageExamScore);
} else System.out.println("No scores to average");
}
}
averageExamScore variable should be a double otherwise it can not stored floating point values
Good Luck !!!
I created a program that enables you to type in four numbers that must have specific requirements:
-must be a multiple of 4 or 6
-if greater than 500, must be a multiple of 10
The program takes the four numbers and gives you the sum of them, the average of them, shows you the smallest of the four numbers and finally the largest of the four numbers.
Now I want to try and display a group that each number belong to. I want these groups if you were wondering:
Group Tens if the number is between 0 and 99
Group Hundreds if the number is between 100 and 999
Group Thousands if the number is between 1000 and 999,999
Group Others if the number is greater than 999,999
My problem is I do not know where I should being placing them into my program (below)
import java.util.Scanner;
public class FourNumbersProgram {
private static int readNumber(String message, Scanner in) {
System.out.println("Enter a numbers divislbe by 4 or 6. No negatives.");
System.out.println("**If greater than 500: must be multiple of 10");
System.out.print(message);
while (!in.hasNextInt()) {
in.next();
System.out.println("Sorry, couldn't understand you!");
System.out.print(message);
}
int a = in.nextInt();
return a;
}
private static int readNumberToMatchCondition(String message, Scanner in) {
int number = 0;
do {
number = readNumber(message, in);
if (number < 500) {
if (number % 4 != 0 && number % 6 != 0) {
System.out.println(number + " not divisible by 4 or 6");
} else {
return number;
}
} else {
if (number % 4 != 0 && number % 6 != 0) {
System.out.println(number + " not divisible by 4 or 6");
} else if (number % 10 != 0) {
System.out.println(number + " is greater than 500 and not divisible by 10");
} else {
return number;
}
}
} while (true);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int randomNumber1 = readNumberToMatchCondition("Enter first number:", in);
int randomNumber2 = readNumberToMatchCondition("Enter second number:", in);
int randomNumber3 = readNumberToMatchCondition("Enter third number:", in);
int randomNumber4 = readNumberToMatchCondition("Enter fourth number:", in);
int sum; // sum of number1, number2, number3, and number4
int avg; // average of number1, number2, number3, and number4
int largest; // largest number of the four integers
int smallest; // smallest number of the four integers
sum = (randomNumber1 + randomNumber2 + randomNumber3 + randomNumber4);
avg = ((sum) / 4);
smallest = randomNumber1;
smallest = (randomNumber2 < smallest) ? randomNumber2 : smallest;
smallest = (randomNumber3 < smallest) ? randomNumber3 : smallest;
smallest = (randomNumber4 < smallest) ? randomNumber3 : smallest;
largest = randomNumber1;
largest = (randomNumber2 > largest) ? randomNumber2 :largest;
largest = (randomNumber3 > largest) ? randomNumber3 :largest;
largest = (randomNumber4 > largest) ? randomNumber4 :largest;
System.out.println();
System.out.println("First number entered: " + randomNumber1); //prints first number entered
System.out.println("Second number entered: " + randomNumber2); //prints second number entered
System.out.println("Third number entered: " + randomNumber3); //prints third number entered
System.out.println("Fourth number entered: " + randomNumber4); //prints fourth number entered
System.out.println();
System.out.println("The sum is: " + sum); //prints sum of four numbers
System.out.println("The average is: " + avg); //prints average of four numbers
System.out.println("The smallest number is: " + smallest); //prints smallest of the four numbers
System.out.println("The largest number is: " + largest); //prints largest of the four numbers
System.out.println();
}
}
Here is a transcript of my code:
my professor gave me this sample of a grouping program (below)
import java.util.Scanner;
public class Prog2 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);// read a number
System.out.println("Enter a number: ");
int number = in.nextInt();
if (number < 0) {
System.out.println("Error: Sorry, no negative numbers allowed.");
System.exit(0);
}
int grp1 = (number / 100) + 1;
int grp2 = (number / 1000) + 1;
int grp3 = (number / 1000000) + 1;
switch (grp1){
case 1: // Group Tens
System.out.println(number + " belongs to Group Tens");
break;
default:
switch (grp2) {
case 1:// Group Hundreds
System.out.println(number + " belongs to Group Hundreds");
break;
default:
switch (grp3) {
case 1:// Group Thousands
System.out.println(number + " belongs to Group Thousands");
break;
default:// Group Others
System.out.println(number + " belongs to Group Others");
}
}
}
in.close();
}
}
Heres a transcript of his code:
I know his program is asking for the user to type in one number and the program groups it. I was wondering how to put something like this into my program. I am confused because I have four numbers that have to be grouped and I'm not sure if I have to repeat something similar to my professors program for all of my four numbers (randomNumber1, randomNumber2, randomNumber3, randomNumber4
Please no positing an entire corrected code! I want to fix it myself and learn!
Your professors program will work for all of your numbers. All you need to do is call the method 4 times. Once for each number. What you need to do is put his code into a method on it's own. (Remember, if he's given it to you as a guide, then he will probably want you to give a go at writing the logic yourself).
Let's say you put his code in a method that looks like:
public void displayNumberGroup(int number)
{
// Displays number group using your prof's code.
}
Then, next, all you need to do is pass each value that you've loaded, into that method. For example: displayNumberGroup(randomNumber1);. This will calculate the grouping for that number. I'll leave it up to you to put this stuff into context, since you've requested to not be spoonfed the answer (which is very commendable!).
Instead of doing randomNumber1, randomNumber2, ect you can make them into an array. By doing that, you can then put a for loop over the given switch and run it 4 times so all of your numbers have groups. If you need me to explain any part of this with a simple example I will, but I know you want to do most of this yourself so if you have any questions let me know.
I've posted this program once before but realized I was overthinking it by adding loops and what not. I've paired it down a bit but still running into problems. The program is supposed to be a change machine. After the user inputs price, the program should round it up to the nearest dollar then output how much change will be dispensed and a count of which coins. The output is completely wrong at this point. I'm very new to programming and I'm at a loss.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price*100);
int paid = (int)(newPrice+1);
int change = (int)(paid - newPrice);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Once newPrice is an int, you can stop casting every line.) Instead of chaining % together, it would be more readable (and less error prone) to subtract off the values you've found:
change -= 25*quarters;
dimes = change / 10;
change -= 10*dimes;
nickels = change / 5;
change -= 5*nickels;
pennies = change;
I think it would help you to understand if you would go through the code by hand and think about what price, newprice, paid, and change are.
newprice is the price round down to the lower dollar.
paid is the cost of the item.
change is the amount you paid minus the cost converted into an integer number of pennies.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price);
int paid = (int)(newPrice+1);
int change = (int)((paid - price) * 100);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
If instruction int paid= (int)(newPrice+1) ; is supposed to be rounding to next dollar, then it should be: int paid= ( newPrice + 99 ) / 100 * 100 ; You don't need to convert to (int) when both operands are already ints. Makes your program slightly illegible. Later, after obtaining the number of quarters by quarters= change / 25 ;(that's correct in your program), you can reduce the amount fromchangewithchange-= quarters * 25 ;`.
This makes calculating dimes exactly the same as quarters, just that using 10 instead of 25. Don't forget reducing the dimes from the pending change again with change-= dimes * 10 ;. You can repeat the process with nickels and the remaining change will be pennies.
If you have any doubt, use a debugger or output each intermediate result with System.out. You can always delete them later once you understand your program's behavior.
This is how I made Java choose what coins I must pay with.
int temp = m;
int quarterCoin = 25;
int x = m/quarterCoin;
m=m-x*quarterCoin;
int dimeCoin = 10;
int z = m/dimeCoin;
m=m-z*dimeCoin;
int nickelCoin = 5;
int y = m/nickelCoin;
m=m-y*nickelCoin;
int pennyCoin = 1;
int w = m/pennyCoin;
m=m-w*pennyCoin;
Instead of giving you the answer/solution to your homework, I am going to help you figure out how to figure it out. :)
In order to adequately debug your software and troubleshoot what's going on, you need to know what your variables are doing. There are two methods:
Attach a debugger - Most IDEs will come with a debugger that will help you accomplish this.
Print out your variables to the console. This is my preferred method. Me and debuggers never have gotten along well together. :)
So, here is what I would do if I were trying to figure your program out:
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// System.out.println("Enter Purchase Price: ");
double price = 5.65d;//scan.nextDouble();
int newPrice = (int) (price * 100);
System.out.println("newPrice: " + newPrice);
int paid = (int) (newPrice + 1);
System.out.println("paid: " + paid);
int change = (int) (paid - newPrice);
System.out.println("change: " + change);
int quarters = (int) (change / 25);
int dimes = (int) ((change % 25) / 10);
int nickels = (int) ((change % 25 % 10) / 5);
int pennies = (int) (change % 25 % 10 % 5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Note: Instead of utilizing the scanner, I just manually entered "5.65" into the price variable just to save time)
Which produces the output:
newPrice: 565
paid: 566
change: 1
Dispensing: 0 Quarters,0Dimes,0Nickels,1Pennies.
Program written by Ashley
So, now you can see what your program is doing wrong. Can you spot it?