Requires: variables, data types, and numerical operators basic input/output logi
ID: 3572974 • Letter: R
Question
Requires:
variables, data types, and numerical operators
basic input/output
logic (if statements, switch statements)
Write a program that presents the user w/ a choice of your 5 favorite beverages (Coke, Water, Sprite, ... , Whatever).
Then allow the user to choose a beverage by entering a number 1-5.
Output which beverage they chose.
If you program uses if statements instead of a switch statement, modify it to use a switch statement.
If instead your program uses a switch statement, modify it to use if/else-if statements.
Modify the program so that if the user enters a choice other than 1-5 then it will output "Error. choice was not valid, here is your money back."
Explanation / Answer
Using switch
BeveragesMenu.java
import java.util.Scanner;
public class BeveragesMenu {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Menu: 1. Coke 2. Water 3. Sprite 4. Fanta 5. Milk Enter your choice: ");
int choice = scan.nextInt();
switch(choice){
case 1: System.out.println("You have choosen Coke");break;
case 2: System.out.println("You have choosen Water");break;
case 3: System.out.println("You have choosen Sprite");break;
case 4: System.out.println("You have choosen Fanta");break;
case 5: System.out.println("You have choosen Milk");break;
default: System.out.println("Error. choice was not valid, here is your money back.");
}
}
}
Using ifelse
BeveragesMenu.java
import java.util.Scanner;
public class BeveragesMenu {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Menu: 1. Coke 2. Water 3. Sprite 4. Fanta 5. Milk Enter your choice: ");
int choice = scan.nextInt();
if(choice== 1) {
System.out.println("You have choosen Coke");
}
else if (choice == 2) {
System.out.println("You have choosen Water");
}
else if (choice == 3) {
System.out.println("You have choosen Sprite");
}
else if (choice == 4) {
System.out.println("You have choosen Fanta");
}
else if (choice == 5) {
System.out.println("You have choosen Milk");
}
else{
System.out.println("Error. choice was not valid, here is your money back.");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.