+ 1
Vending machin problem
i cant pass test case 6 idk what's the problem.. import java.util.Scanner; public class Program { public static void main(String[] args) { String[] menu = {"Tea", "Espresso", "Americano", "Water", "Hot Chocolate"}; Scanner sc = new Scanner(System.in); System.out.print(""); int choice = sc.nextInt(); if (choice >= 1 && choice <= 5) { String chosenDrink = menu[choice]; System.out.println( chosenDrink); } else { System.out.println("Invalid"); } } }
4 Antworten
+ 1
There is many ways to solve this but one way is to replace your if statement with this:
choice >= 0 && choice < menu.length
Checks if your input is higher than or equal 0 and less than your menu array length
0
Thanks🙌
0
No problem👍
0
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
String[] menu = {"Tea", "Espresso", "Americano", "Water", "Hot Chocolate"};
Scanner sc = new Scanner(System.in);
System.out.print("Enter your choice (1-5): ");
if (sc.hasNextInt()) {
int choice = sc.nextInt();
if (choice >= 1 && choice <= 5) {
String chosenDrink = menu[choice - 1];
System.out.println("You chose: " + chosenDrink);
} else {
System.out.println("Invalid choice");
}
} else {
System.out.println("Invalid input");
}
}
}