0

Java intermediate -> exceptions handling problem

Import java.util.Scanner; public class Main { public static void main(String[] args) { // Declare and initialize the product categories array String[] categories = {"PCs", "Notebooks", "Tablets", "Phones", "Accessories"}; // Create a Scanner object to take input from the user Scanner scanner = new Scanner(System.in); // Take the index as input int n = scanner.nextInt(); try { // Try to access the element at the given index System.out.println(categories[n]); } catch (ArrayIndexOutOfBoundsException e) { // If an exception occurs (index out of bounds), print "Wrong Option" System.out.println("Wrong Option"); } } } The above code is not satisfying test cases. Can anyone tell me the correct code plz It is a bug 🐛

2nd Oct 2024, 3:00 AM
BHANUTEJA
BHANUTEJA - avatar
4 Respostas
+ 4
BHANUTEJA 'import' lowercase, not 'Import' aside from this typo, I think that there is indeed a bug in the lesson. "Accessories" letter 'А' seems to be typed with a non standard character. If I delete the original word and retype it, it is flagged wrong. But if I copy pasted the word "Accessories" from the problem description, the test passes. If it is intentional, it's not funny at all. But it's a good learning challenge. Just because it looks the same doesn't mean it is the same. It's the basis of many phishing attacks. look here: https://sololearn.com/compiler-playground/c9jH1nN7bJfe/?ref=app
2nd Oct 2024, 4:27 AM
Bob_Li
Bob_Li - avatar
+ 1
Bob_Li Thank you so much for your support. 😊
4th Oct 2024, 2:24 AM
BHANUTEJA
BHANUTEJA - avatar
0
I copy-paste it to SL playground and I have no problem with 'Accessories'
2nd Oct 2024, 7:42 PM
zemiak
0
try { // Take the index as input int n = scanner.nextInt(); // error! // Try to access the element at the given index System.out.println(categories[n]); } catch (ArrayIndexOutOfBoundsException e) { // If an exception occurs (index out of bounds), print "Wrong Option" System.out.println("Wrong Option"); } catch (Exception e) { // Block of code to handle errors System.out.println("Something went wrong."); } finally { //System.out.println("The 'try catch' is finished."); }
2nd Oct 2024, 11:02 PM
SoloProg
SoloProg - avatar