+ 1

Problem in the Java Reverse a String Code Project

Hello, I want to solve the Reverse a String code Project but I am getting an exception that says "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 17 out of bounds for length 17 at Program.main(Program.java:13)" I looked up what the exception meant and Oracle said it means that "The index is either negative or greater than or equal to the size of the array," but I don't understand how I wrote the code to be greater than or equal to the size of the array. (Please see the code below.) Does anyone know why it's throwing this exception? Thanks, Iulia import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String text = scanner.nextLine(); char[] arr = text.toCharArray(); //int x = arr.length; for (int i = arr.length; i > 0; i--) { System.out.println(arr[i]); //arr--; } } }

29th Aug 2022, 6:44 PM
Iulia
4 Respuestas
+ 3
Guys, thank you, So for: for (int i = arr.length; i>0; i--) { System.out.println(arr[i-1]); } from you need i > 0 && (arr[i-1]) because arr is the length of the array and you're printing from the last character backwards and for for (int i = arr.length-1; i>=0; i--) { System.out.println(text.charAt(i)); } You need i = arr.length-1 && i >= 0 because i goes all the way down to 0 and in that case you'll just be printing i and arr[i-1] means the previous character in the array. I get it! Ok, thank you all, Ę ~ J, SoloProg and Jayakrishna🇮🇳 for answering my questions!!
29th Aug 2022, 7:31 PM
Iulia
0
for (int i=arr.length; i>0; i--) System.out.println(arr[i-1]);
29th Aug 2022, 7:02 PM
SoloProg
SoloProg - avatar
0
Index values starts from 0. So arr.length returns the array length. Then valid indexes are 0 to arr.length-1 only. arr[arr.length] raise exception due to index is equal to size of array.
29th Aug 2022, 7:05 PM
Jayakrishna 🇮🇳