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
2 odpowiedzi
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
0
My answer Working try { // Attempt to access the element at index 'choice' String selectedCategory = categories[choice]; System.out.println(selectedCategory); } catch (ArrayIndexOutOfBoundsException e) { // Handle the case where 'choice' is out of array bounds System.out.println("Wrong Option"); } catch (Exception e) { // Catch any other unexpected exceptions System.out.println("Something went wrong"); } finally { scanner.close(); // Ensure scanner is closed to prevent resource leak } } }
27th Jun 2024, 12:16 AM
PYSCODES
PYSCODES - avatar