Calculating change from 2 inputs by a user - java

i am trying to output the minimum amount of notes needed from two inputs. one being the cost and the other being the amount handed over by the customer.
so if i enter 400 and then 500, it should say 2 $50 dollars notes.
or if i enter 60 and then 80, it should say 1 $20 dollar note.
this is a small bit of my code:
import java.util.Scanner;
public class bank {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter amount due: ");
int amount = input.nextInt();
System.out.println("Amount tendered: ");
int tmp = input.nextInt();
int change;
if(amount >= 50)
{
change =(tmp - amount)/50;
System.out.println (change + " $50 bills");
}
if(amount >= 20)
{
change =(tmp - amount)/20;
System.out.println (change + " $20 bills");
}

You can achieve it by using mod operator %
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter amount due: ");
int amount = input.nextInt();
System.out.println("Amount tendered: ");
int tmp = input.nextInt();
int change;
int diff = tmp - amount;
if (diff % 50 == 0) {
change = diff / 50;
System.out.println(change + " $50 bills");
}
else if (diff % 20 == 0) {
change = diff / 20;
System.out.println(change + " $20 bills");
}
}

Once you calculate the amount of change in a value of a bill, you need to lower the amount of change required. This is done in the code changeRequired = changeRequired - change;
System.out.println("Amount tendered: ");
int tmp = input.nextInt();
int changeRequired = tmp - amount;
int change;
if(amount >= 50)
{
change =(changeRequired)/50;
changeRequired = changeRequired - change;
System.out.println (change + " $50 bills");
}
if(amount >= 20)
{
change =(changeRequired )/20;
changeRequired = changeRequired - change;
System.out.println (change + " $20 bills");
}

Once you get your change which is the variable amount, you can use the following code to find out how many notes of each of the $50, $20, $10, $5, $1 there are in the change. The number of notes is minimal.
numOf50 = 0; // number of $50 dollar bills, the rest is similar.
numOf20 = 0; // ...
numOf10 = 0; // ...
numOf5 = 0;
numOf1 = 0;
if (amount / 50 > 1){
numOf50 += (amount / 50);
amount %= 50; // update the amount with the remainder
}
else if (amount / 20 > 1){
numOf20 += (amount /20);
amount %= 20;
}
else if (amount / 10 > 1){
numOf10 += (amount / 10);
amount %= 10;
}
else if (amount / 5 > 1){
numOf5 += (amount / 5);
amount %= 5;
}
else if (amount <=5 && amount >0){
numOf1 = amount;
}
// output is trivial, omitted.
Haven't tested on a machine but it should work or give you an idea.

Related

Terminate program with letter Q

I'd like to terminate the program by typing Q whenever. I can't place it in "diceChosen" because it's an integer. I've tried different things but nothing works for me.
Scanner userInput = new Scanner(System.in);
int wins = 0;
int losses = 0;
int diceOne = 0;
int diceTwo = 0;
int diceThree = 0;
int sum = 0;
System.out.println("Välkommen till spelet 12. Du ska slå 1-3 tärningar och försöka få summan 12...");
for (int counter = 0; counter < 3; counter++) {
System.out.printf("%nAnge vilken tärning du vill slå[1,2,3](avsluta med q): ");
int diceChosen = userInput.nextInt();
if (diceChosen == 1)
diceOne = (int)(Math.random() * 6) + 1;
if (diceChosen == 2)
diceTwo = (int)(Math.random() * 6) + 1;
if (diceChosen == 3)
diceThree = (int)(Math.random() * 6) + 1;
sum = diceOne + diceTwo + diceThree;
if (sum == 12)
++wins;
if (sum > 12)
++losses;
System.out.printf("%d %d %d sum: %d #vinst: %d #förlust: %d", diceOne, diceTwo, diceThree, sum, wins, losses);
}
Since you can not use try and catch other alternative can be by changing your userInput.nextInt() to userInput.nextLine(); so it can detect when Q is pressed if Q is not pressed then we convert String to int so it can calculate the logic with Integer.parseInt(diceChosen);
All the code
while (true) {
for (int counter = 0; counter < 3; counter++) {
System.out.printf("%nAnge vilken tärning du vill slå[1,2,3](avsluta med q): ");
String diceChosen = diceChosen = userInput.nextLine();
int diceChosenToInteger = 0;
if (diceChosen.equalsIgnoreCase("Q")) {
System.exit(0);
} else {
diceChosenToInteger = Integer.parseInt(diceChosen);
}
if (diceChosenToInteger == 1)
diceOne = (int) (Math.random() * 6) + 1;
if (diceChosenToInteger == 2)
diceTwo = (int) (Math.random() * 6) + 1;
if (diceChosenToInteger == 3)
diceThree = (int) (Math.random() * 6) + 1;
sum = diceOne + diceTwo + diceThree;
if (sum == 12)
++wins;
if (sum > 12)
++losses;
System.out.printf("%d %d %d sum: %d #vinst: %d #förlust: %d", diceOne, diceTwo, diceThree, sum, wins, losses);
}
}
}
}
You could have an additional question asking the user if they would like to play again:
import java.util.Random;
import java.util.Scanner;
public class Main {
private static int getIntegerInput(Scanner scanner, String prompt, int minValue, int maxValue) {
System.out.print(prompt);
int validInteger = -1;
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
validInteger = scanner.nextInt();
if (validInteger >= minValue && validInteger <= maxValue) {
break;
} else {
System.out.printf("Error: Please enter an integer between %d and %d inclusive%n", minValue, maxValue);
System.out.print(prompt);
}
} else {
System.out.printf("Error: Please enter an integer between %d and %d inclusive%n", minValue, maxValue);
System.out.print(prompt);
scanner.next();
}
}
return validInteger;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int gamesPlayed = 0;
int wins = 0;
System.out.println("Welcome! You must roll 1-3 dice and try to get the sum 12...");
while (true) {
System.out.printf("Game %d:%n", ++gamesPlayed);
int numDiceRolls = getIntegerInput(scanner, "How many dice do you want to roll? ", 1, 3);
int total = 0;
for (int i = 1; i <= numDiceRolls; i++) {
int roll = new Random().nextInt(6) + 1;
System.out.printf("Roll %d: %d%n", i, roll);
total += roll;
}
System.out.printf("The total for this game was %d%n", total);
if (total == 12) {
System.out.println("You won this game!");
wins++;
} else {
System.out.println("You lost this game!");
}
System.out.print("Enter q to quit or anything else to play again: ");
String playAgain = scanner.next();
if (playAgain.toLowerCase().equals("q")) {
break;
}
}
System.out.printf("You won %d time(s) and lost %d time(s)", wins, gamesPlayed - wins);
}
}
Example Usage:
Welcome! You must roll 1-3 dice and try to get the sum 12...
Game 1:
How many dice do you want to roll? 5
Error: Please enter an integer between 1 and 3 inclusive
How many dice do you want to roll? 3
Roll 1: 1
Roll 2: 2
Roll 3: 6
The total for this game was 9
You lost this game!
Enter q to quit or anything else to play again: a
Game 2:
How many dice do you want to roll? 3
Roll 1: 6
Roll 2: 3
Roll 3: 3
The total for this game was 12
You won this game!
Enter q to quit or anything else to play again: q
You won 1 time(s) and lost 1 time(s)

One input doesn't work, while the rest does

The user must input the total purchase amount and how old they are, and then calculate the final payment.
If the total amount is $100 or over, there is a 20% discount off the total price. If the age is 65 or older, there is a 10% discount off the total price.
double discount1 = 0.10;
double discount2 = 0.20;
double totalPrice = 0.0;
double finalPrice = 0.0;
System.out.print("Enter total amount: ");
double purchase = input.nextDouble();
System.out.print("Enter age: ");
int age = input.nextInt();
if (purchase >= 100) {
totalPrice = purchase * discount2;
finalPrice = purchase - totalPrice;
System.out.print("The final amount is $" + finalPrice);
}
else if (purchase < 100 && age < 65) {
System.out.println("The final amount is $" + purchase);
}
else if (age >= 65) {
totalPrice = purchase * discount1;
finalPrice = purchase - totalPrice;
System.out.print("The final amount is $" + finalPrice);
}
The user would input 200 as the total amount and 75 as the age. The output is supposed to be $140.00. However, I receive the output as $160.00.
The first if statement will be executed first. Because the price is above 100. So the other statements will not be executed. Try to change the if expressions because of thats the problem why it's not giving the result you may expect
My approach would be to add all of the discounts together and then multiply once at the end.
Than you can add other discounts if needed
double totalDiscount = 0.0;
if (purchase >= 100) {
totalDiscount += discount2;
}
if (age >= 65) {
totalDiscount += discount1;
}
totalPrice = purchase * (1.0 - totalDiscount);
System.out.print("The final amount is $" + totalPrice);
You nee to change below code,
because when ever price is more then 100 it will run first if block and wont enter into last block.
so change it in below manner :-
if (purchase >= 100 && age < 65) {
totalPrice = purchase * discount2;
finalPrice = purchase - totalPrice;
System.out.print("The final amount is $" + finalPrice);
}
else if (purchase < 100 && age < 65) {
System.out.println("The final amount is $" + purchase);
}
else if (purchase < 100 &&age >= 65) {
totalPrice = purchase * discount1;
finalPrice = purchase - totalPrice;
System.out.print("The final amount is $" + finalPrice);
}
else if (age >= 65) {
totalPrice1 = purchase * discount2;
totalPrice = purchase * discount1;
finalPrice = purchase - totalPrice - totalPrice1 ;
System.out.print("The final amount is $" + finalPrice);
}

How to print proper minimum and maximum from user input

I am trying to write a program that allows a user to enter in a number of random grades they want to display along with the sum, average, minimum and maximum of the generated list. The grades range from 60 - 100.
The program is printing the min properly and the sum is adding up the previously generated sum along with the newly generated one. How can I change it so that it give the correct output for the minimum and so that is stops adding the previou sum to the new one? Any help would be appreciated.
The image link for the output shows the minimum output issue. The min should be 66.0 but it says 59.0.
output
import java.util.Scanner;
public class A03C
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("How many scores? ");
int howMany = input.nextInt();
double score = 0;
double sum = 0;
double average = 0;
double max = 0;
double min = 60;
while (howMany > 0)
{
for (int i = 1; i <= howMany; i++)
{
score = 60 + (int)(Math.random() * ((100 - 60) +1));
if (letterGrade(score));
sum += score++;
average = (sum/howMany);
if (score > max)
max = score;
if (score < max)
min = score;
}
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
System.out.println("Max: " + (max - 1));
System.out.println("Min: " + (min - 1));
System.out.println("How many scores? ");
howMany = input.nextInt();
}
}
public static boolean letterGrade(double score)
{
if (score >= 92.0)
System.out.println(score + " is an A");
else if (score >= 83.0)
System.out.println(score + " is a B");
else if (score >= 75.0)
System.out.println(score + " is a C");
else
System.out.println(score + " is an F");
return false;
}
}
Just clean the sum variable after the execution, also I changed the return of the letterGrade to true:
import java.util.Scanner;
public class A03C {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many scores? ");
int howMany = input.nextInt();
double score = 0;
double sum = 0;
double average = 0;
double max = 0;
double min = 60;
while (howMany > 0) {
for (int i = 1; i <= howMany; i++) {
score = 60 + (int) (Math.random() * ((100 - 60) + 1));
if (letterGrade(score))
sum += score++;
average = (sum / howMany);
if (score > max)
max = score;
if (score < max)
min = score;
}
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
System.out.println("Max: " + (max - 1));
System.out.println("Min: " + (min - 1));
System.out.println("How many scores? ");
sum = 0;
howMany = input.nextInt();
}
}
public static boolean letterGrade(double score) {
if (score >= 92.0)
System.out.println(score + " is an A");
else if (score >= 83.0)
System.out.println(score + " is a B");
else if (score >= 75.0)
System.out.println(score + " is a C");
else
System.out.println(score + " is an F");
return true;
}
}
Before continue, i definitely think that you should read #joe C comment.
As i understand you are a beginner, i will explain the changes i did.
import java.util.Scanner;
public class A03C
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("How many scores? ");
int howMany = = input.nextInt();
double score = 0;
double sum = 0;
double average = 0;
double max = 60;
double min = 100;
while (howMany > 0)
{
for (int i = 1; i <= howMany; i++)
{
score = 60 + (int)(Math.random() * ((100 - 60) +1));
letterGrade(score);
sum += score++;
average = (sum/howMany);
if (score > max)
max = score;
if (score < min)
min = score;
}
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
System.out.println("Max: " + (max - 1));
System.out.println("Min: " + (min - 1));
System.out.println("How many scores? ");
howMany = input.nextInt();
}
}
public static void letterGrade(double score)
{
if (score >= 92.0)
System.out.println(score + " is an A");
else if (score >= 83.0)
System.out.println(score + " is a B");
else if (score >= 75.0)
System.out.println(score + " is a C");
else
System.out.println(score + " is an F");
}
}
Starting with the function letterGrade. Since the function always return false and just prints a sentence, you can replace boolean to void.
Another mistake you did was that if you want to find max and min, the variables shall take the inverse of you want. So the variable max shall take the minimum variable (60) and the maximum value (100).
Finally, in order to change variables max and min you must compare the new value to their current value. This is, to change min value, for example, you have to compare score with current min.
Hope it helps.

Calculate total amount

When try to run I got wrong answer. What's wrong in my program?
Got answer is only for discount_amount not able to get total amount.
Scanner input = new Scanner(System.in);
double dicount_amount = 0;
double discount1 = 0;
double total = 0;
System.out.println("Enter the cost of the software: ");
double cost = input.nextDouble();
System.out.println(" Enter the quantity sold: ");
int quantity = input.nextInt();
if (cost > 0 && quantity > 0){
if(quantity >= 10 && quantity >=19){
discount1 = 20/100;
}
else if(quantity >= 20 && quantity >=49){
discount1 = 30/100;
}
else if(quantity >= 50 && quantity >=99){
discount1 = 40/100;
}
else if(quantity <=100){
discount1 = 50/100;
}
}
else {
System.out.println( " please enter valid input ");
}
double total1 = cost * quantity;
dicount_amount = total1 * discount1;
total= total1 - dicount_amount;
System.out.println("Total Cost: " + total);
}
Simplest thing you can do is not to divide discount1 = 20/100;, instead that you can set directly value discount1 = 0.2;
Also you should check your if statement
Example:
if(quantity >= 10 && quantity >=19)
is equal to
if(quantity >=19)
I think you want to check if quantity is between. So you should use
if(quantity >= 10 && quantity <=19)
Guess what was your mistake? You were dividing int by int and you are excepting a double result. Typecast the division to double or do 20.0/100. Also, I assume you are want to give a discount if the quantity is between 10 and 19. What you have been doing doesn't make sense because every time you run your program it will never fall in else if() statement because you are setting quantity>=19 in if statement.
here are few changes I made in your code :
Scanner input = new Scanner(System.in);
double dicount_amount = 0;
double discount1 = 0;
double total = 0;
System.out.println("Enter the cost of the software: ");
double cost = input.nextDouble();
System.out.println(" Enter the quantity sold: ");
int quantity = input.nextInt();
if (cost > 0 && quantity > 0){
if(quantity >= 10 && quantity <=19){
discount1 = (double)20/100;
}
else if(quantity >= 20 && quantity <=49){
discount1 = (double)30.0/100;
}
else if(quantity >= 50 && quantity <=99){
discount1 = (double)40.0/100;
}
else if(quantity >=100){
discount1 = (double)50.0/100;
}
}
else {
System.out.println( " please enter valid input ");
}
double total1 = cost * quantity;
dicount_amount = total1 * discount1;
total= total1 - dicount_amount;
System.out.println("Total Cost: " + total);
Output :
Enter the cost of the software:15
Enter the quantity sold:16
Total Cost: 192.0

Java change app

So I have Been working on a Program and it has been awhile since I have last used java. I was wondering how to get my program to accept decimals. I have tried looking it up but I couldn't find anything helpful and anything I really understood.Below is what I have done so far...
package test;
import java.util.Scanner;
/**
*
* #author Thao
*/
public class Test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );
double cash; // double makes it allow decimals
int hundred;
int twenty;
int ten;
int toonies ;
int lonies;
int quarters;
int dimes;
int nickels;
int pennies;
int money;
int change;
System.out.println();// blank line
System.out.print("Hello ");
System.out.println();
System.out.println("Please enter a number with no decimal places ");
cash = input.nextInt(); // read first integer
System.out.println("you have Entered "+cash);
hundred = 100;
change = (int)hundred - (int)cash;
System.out.println("The change from $100.00 is:" + (double)change);
change = 100 * change; // multiply cash by 100
money = (int)change; //cash is now a int
twenty = money / 2000;
money = money - (twenty * 2000);
toonies = money / 200; // money is multiplied by 100 than / by 200
money = money - (toonies * 200); // ex. money = 1586 - (7.93 * 200 )
lonies = money / 100 ;
money = money - (lonies * 100);
quarters = money / 25;
money = money - (quarters * 25);
dimes = money / 10;
money = money - (dimes * 10);
nickels = money / 5;
money = money - (nickels * 5);
pennies = money / 1;
money = money - (pennies * 1);
if(twenty>0){
System.out.println();
System.out.print("You will have this many Twenties ");
System.out.print(twenty + ".");
}
else{
}
if(toonies>0){
System.out.println();
System.out.print("You will have this many Toonies ");
System.out.print(toonies + ".");
System.out.println();
}
else{
}
if(lonies>0){
System.out.print(" You will have this many Lonies ");
System.out.print(lonies + ".");
System.out.println();
}
else{
}
if(quarters>0){
System.out.print(" You will have this many quarters ");
System.out.print(quarters + ".");
System.out.println();
}
else{
}
if(dimes>0){
System.out.print(" You will have this many dimes ");
System.out.print(dimes + ".");
System.out.println();
}
else{
}
if(dimes>0){
System.out.print(" You will have this many nickels ");
System.out.print(nickels);
System.out.println();
}
else{
}
if(pennies>0){
System.out.print(" You will have this many pennies ");
System.out.print(pennies);
System.out.println();
}
else{
}
System.out.println();
System.out.println("Thank you for using my app ");
}
}
You can use double or float for the variable's data type. To read a double from your input you would do:
double cash = input.nextDouble();
or
float cash = input.nextFloat();

Categories