-
Notifications
You must be signed in to change notification settings - Fork 627
/
Copy pathCandyVendor.java
68 lines (47 loc) · 1.53 KB
/
CandyVendor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.Scanner;
public class CandyVendor {
private int candies;
private int money;
public CandyVendor(int can) {
this.candies = can;
this.money = 0;
}
public int buy(int amt) {
if (amt < 1 || candies == 0) {
return 0;
}
if (amt > candies) {
amt = candies;
}
candies -= amt;
money += amt;
return amt;
}
public void print() {
System.out.println("Candies left: " + candies);
System.out.println("Money collected: " + money);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the candy vending machine!");
int candies = sc.nextInt();
CandyVendor vendor = new CandyVendor(candies);
while (true) {
System.out.println("How much money do you want to insert?");
int money = sc.nextInt();
int candiesDispensed = vendor.buy(money);
if (candiesDispensed == 0) {
System.out.println("Not enough candies or money!");
} else {
System.out.println("Here are your candies!");
}
vendor.print();
System.out.println("Do you want to buy more candy? (y/n)");
String choice = sc.next();
if (!choice.equalsIgnoreCase("y")) {
break;
}
}
sc.close();
}
}