0

Why is the code not printing out what i want

The code works fine when i input values from 0 to 4 but when i input any other number for example 9 this is what i get "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 9 out of bounds for length 5 at Program.main(Program.java:10)" the output im expecting is "Invalid" The code ⬇️⬇️ 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); //your code goes here int choice = sc.nextInt(); if(choice>=0 || choice<=4) System.out.println(menu[choice]); // else if (choice<0 || choice>4) // System.out.println("Invalid"); else System.out.println("Invalid"); } }

13th Feb 2023, 9:33 AM
Nowak March
1 Odpowiedź
+ 3
Valid index length is 0 to 4 only for menu array. Because it's length is 5. So value 9 is out of range for index value..
13th Feb 2023, 9:45 AM
Jayakrishna 🇮🇳