In: Computer Science
Write a short, java program that interacts with the user asking them to buy an xbox series x or PS5 and does the following:
Your program should combine all of these into one cohesive, interactive program with all the parts working together. In your program description, be sure to describe what your program does.
I have created A TestProgram class with double, int & String variable, taking inputs from user, if-else-if ladder and nested if as well with inline comments to explain the logic.
Do let me know in comments in case of any doubt.
import java.util.Scanner;
public class TestProgram {
final double fixedXboxPrice = 5000.0, fixedPs5Price = 5100.0;
String welcomeStr = "Welcome to Play Station & XBOX world";
int qty;
double finalPrice;
public static void main(String[] args) {
TestProgram obj = new TestProgram();
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name:");
String name = sc.nextLine();
System.out.println("Welcome "+name+"!");
obj.startProgram();
}
public void startProgram() {
Scanner sc = new Scanner(System.in);
System.out.println(welcomeStr);
// this loop will run until user selects option 3 from given menu
while (true) {
System.out.println("Choose the option from below menu:");
System.out.println("1. XBOX Series");
System.out.println("2. PS5");
System.out.println("3. Exit");
System.out.println("Enter 1 or 2 or 3:");
int choice = sc.nextInt();
if (choice == 1) {
System.out.println("Enter quantity of XBOX");
qty = sc.nextInt();
calcDiscount(qty, fixedXboxPrice, choice);
} else if (choice == 2) {
System.out.println("Enter quantity of PS5");
qty = sc.nextInt();
calcDiscount(qty, fixedPs5Price, choice);
} else if(choice == 3){
System.exit(0);
}else{
System.out.println("Enter correct choice.");
}
}
}
//to demonstrate if-else-if ladder, let's provide discount to user based on below criteria and display final effective price
// quantity <= 5 then discount of flat 10
// quantity > 5 then 1% discount
// quantity > 10 then 5% discount
// quantity > 15 then 7% discount
// quantity > 20 then 9 % discount and additional discount of flat 50 in case of ps5
public void calcDiscount(int qty, double price, int choice) {
if (qty > 20) {
finalPrice = price - price * 0.09;
if (choice == 2) // nested if
finalPrice = finalPrice - 50;
} else if (qty > 15) {
finalPrice = price - price * 0.07;
} else if (qty > 10) {
finalPrice = price - price * 0.05;
} else if (qty > 5) {
finalPrice = price - price * 0.01;
} else if (qty > 0) {
finalPrice = finalPrice - 10;
} else {
System.out.println("Quantity entered must be at least 1.");
return; // return control only. in this case no need to print price because qty is <= 0.
}
System.out.println("Final price after discount : "+finalPrice);
}
}
Screenshot of code:
Output: