+ 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"); } } }

2nd Oct 2023, 2:57 PM
Cord Ian Moraleta
Cord Ian Moraleta - avatar
4 Respostas
+ 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
2nd Oct 2023, 5:32 PM
JavaBobbo
JavaBobbo - avatar
0
Thanks🙌
2nd Oct 2023, 5:53 PM
Cord Ian Moraleta
Cord Ian Moraleta - avatar
0
No problem👍
2nd Oct 2023, 5:59 PM
JavaBobbo
JavaBobbo - avatar
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"); } } }
4th Oct 2023, 7:58 AM
Blunderking2023
Blunderking2023 - avatar