+ 1
Hi, can someone help me with this? (java)
I am doing a program that reverse a string, the code: import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String text = scanner.nextLine(); String a = ""; char[] arr = text.toCharArray(); for (int x=arr.length; x>=0; x--) { a += arr [x]; } System.out.println (a); } } and in the line 10 (a+=arr [x] ) I have an error, but I don't know how can I fix it, does anyone know the answer?
2 Respostas
+ 4
It should be like so,
x = arr.length - 1
Because suppose we have
arr = "Pablo"
arr.length = 5 (0ut of index error)
But array starts with 0 so we know that the max index we can have for "Pablo" is 4.
+ 1
thanks, I understand it now