Write a program that determines the change to be dispensed from a vending machin
ID: 441228 • Letter: W
Question
Write a program that determines the change to be dispensed from a vending machine. An item in the machine can cost between 25 cents and a dollar, in 5-cent increments(25,30,35,..90,95,100), and the machine accepts only a single dollar to pay for the item. For example, a possible sample dialog might be Enter a price for item (from 25 cents to a dollar, in 5-cent increments): 45 You bought and item for 45 cents and gave me a dollar, so your change is 2 quarters, 0 dimes, and 1 nickles. Submit the program and the output for these three inputs: 30, 65, and 100.Explanation / Answer
This is the answer for your que..
I did it using eclispe ..It works fine..
VendingMachine Class
import java.util.Scanner;
public class VendingMachine {
/**
* @param args
*/
//Method to calculate change to be return.
public static String calculateChange(int price)
{
int nikels=0;
int dims=0;
int quaters=0;
int remaining=100 - price;
while (remaining>0)
{
if(remaining / 25 >0)
{
quaters=remaining / 25;
remaining=remaining % 25;
}
else if(remaining /10 > 0)
{
dims=remaining / 10;
remaining=remaining % 10;
}
else if(remaining / 5 > 0)
{
nikels=remaining / 5 ;
remaining = remaining % 5;
}
}
return quaters+" Quaters "+dims+" Dims "+nikels+" Nikels";
}
//Main method to implement vending machine
public static void main(String[] args) {
// TODO Auto-generated method stub
int price=0;
Scanner sc=new Scanner(System.in);
do
{
System.out.println("Enter a price for item (from 25 cents to a dollar, in 5-cent increments): ");
price=sc.nextInt();
if(price<25)
{
System.out.println("Please enter a price that is greater that 25 cents");
}
else if(price % 5 != 0 )
{
System.out.println("Vending Machine can only take price in 5-cent increments from 25 cents");
System.out.println("please enter one of following: 30 35 40 45 ... 1dollar");
}
}
while(price<25 || price%5 != 0);
System.out.println("You have selected item of price :"+price+" and You have given $1");
System.out.println("so your change is :"+calculateChange(price));
}
}
Output :
1 -----For 35
Enter a price for item (from 25 cents to a dollar, in 5-cent increments): 35You have selected item of price :35 and You have given $1
so your change is :2 Quaters 1 Dims 1 Nikels
2 ------for 65
Enter a price for item (from 25 cents to a dollar, in 5-cent increments): 65You have selected item of price :65 and You have given $1
so your change is :1 Quaters 1 Dims 0 Nikels
3 ----- for 100
Enter a price for item (from 25 cents to a dollar, in 5-cent increments): 100You have selected item of price :100 and You have given $1
so your change is :0 Quaters 0 Dims 0 Nikels
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.