-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShoppingCart.java
More file actions
95 lines (84 loc) · 3.02 KB
/
ShoppingCart.java
File metadata and controls
95 lines (84 loc) · 3.02 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import java.util.Scanner;
public class ShoppingCart{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int[] cart = new int[15];
boolean addMore = true;
int totalAmout = 0;
// Print selection options
System.out.println("Available Items:");
System.out.println("1. 100");
System.out.println("2. 250");
System.out.println("3. 75");
System.out.println("4. 300");
System.out.println("5. 120\n");
// Loop will be executed until cart is empty or user exits by him/her self.
for(int i = 0 ; i < cart.length && addMore ; ){
System.out.print("Enter item number to add: ");
if(!sc.hasNextInt()){
System.out.println("Enter a number from given options.");
sc.next();
continue;
}
int choice = sc.nextInt();
switch(choice){
case 1:
cart[i] = 100;
break;
case 2:
cart[i] = 250;
break;
case 3:
cart[i] = 75;
break;
case 4:
cart[i] = 300;
break;
case 5:
cart[i] = 120;
break;
default:
addMore = true;
System.out.println("Invalid choice.");
continue;
}
System.out.print("Add another item? (y/n): ");
char addAnotherItem = sc.next().trim().toLowerCase().charAt(0);
// Exit loop if cart is full or user exits.
switch(addAnotherItem){
case 'Y':
case 'y':
i++;
if(i == cart.length){
System.out.println("\nYou cannot put more items in the cart because it's full now!!!");
addMore = false;
}else{
addMore = true;
}
break;
case 'n':
case 'N':
addMore = false;
break;
default:
addMore = false;
}
}
// Print all the items purchesed
System.out.print("\nItems purchased : ");
for(int item:cart){
if(item == 0) break;
System.out.print(" " + item);
totalAmout += item;
}
System.out.println("\nTotal = " + totalAmout);
// Calculate discount amount
int discount = totalAmout > 500 ? ( (totalAmout * 10) / 100 ) : 0;
System.out.println("Discount = " + discount);
// Subtract discount from the total amount.
totalAmout = totalAmout - discount;
System.out.println("Final amount = " + totalAmout);
// Close Scanner object to stop any kind of memory leak.
sc.close();
}
}