Am I doing the Try/Catch exercise correct | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Am I doing the Try/Catch exercise correct

I am doing this Try/Catch exercise and not sure if I am doing this right. I know it's looking for out of bounds inputs but was wondering if a for loop was needed for this as I referred to another example. I am passing all cases except for one. Help me if able to please import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int choice = scanner.nextInt(); String[] categories = {"PCs", "Notebooks", "Tablets", "Phones", "Аccessories"}; //complete the code try { int a[] = new int[5]; for (int i = 0; i < 5; i++){ if(choice == i){ System.out.println(categories[i]); } } } catch(Exception e) { System.out.println("Wrong Option"); } } }

13th May 2021, 4:02 PM
Curtis Chadwell
Curtis Chadwell - avatar
1 Answer
0
Update to this issue. I had to simply increase the iteration range in the for loop import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int choice = scanner.nextInt(); String[] categories = {"PCs", "Notebooks", "Tablets", "Phones", "Аccessories"}; //complete the code try { int a[] = new int[5]; for (int i = 0; i <=7; i++){ if(choice == i){ System.out.println(categories[i]); } } } catch(Exception e) { System.out.println("Wrong Option"); } } }
14th May 2021, 9:53 AM
Curtis Chadwell
Curtis Chadwell - avatar