+ 1

How can I print the default statement using multi-dimensional arrays?

I NEED HELP WITH MY CODE! This is my code: import java.util.Scanner; class MyClass { public static void main(String[ ] args) { Scanner myVar = new Scanner(System.in); int [][] choices = { {1, 2, 3, 4}, {5}, {6, 7, 8, 9} }; int chicken = choices[myVar.nextInt()][myVar.nextInt()]; switch(chicken) { case 1: System.out.println("Baked Chicken"); break; case 2: System.out.println("Fried Chicken"); break; case 3: System.out.println("Curry Chicken"); break; case 4: System.out.println("Rotisserie Chicken"); break; case 5: System.out.println("Stew Chicken"); break; case 6: System.out.println("Jerk Chicken"); break; case 7: System.out.println("Cooked Chicken"); break; case 8: System.out.println("Undercooked Chicken"); break; case 9: System.out.println("Overcooked Chicken"); break; default: System.out.println("Raw Chicken"); } } } The problem with my code is that the if someone puts an invalid set of numbers in the user input, the multi-dimensional array will output an error instead of the default statement. Basically, I need to print the default statement if the user inputs an invalid set of numbers in the multi-dimensional array.

25th Jan 2023, 10:49 PM
Micah Thomas
2 Answers
+ 7
You can handle the ArrayIndexOutOfBounds exception using a try-catch block, and assign a non-existent case value to your case variable in the catch block so that your program arrives at the default case. There could be other designs that would better suit this type of user selection use case, but I'm operating under the assumption that there is a requirement for arrays to be used. https://code.sololearn.com/c9W08cxUW37S/?ref=app Ref: https://www.tutorialspoint.com/How-to-handle-Java-Array-Index-Out-of-Bounds-Exception
26th Jan 2023, 12:57 AM
Hatsy Rei
Hatsy Rei - avatar