-1

I am trying to write code in java to reverse string enter by user the program runs fine without any errors but as I press enter after entering the string it show the error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12 at javaprograms.JavaPrograms.main(JavaPrograms.java:16) C:\Users\hp\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1 BUILD FAILED (total time: 8 seconds)"

Here is My code:

   package javaprograms;
   import java.util.Scanner;
   public class JavaPrograms {
   public static void main(String[] args) {
   Scanner s=new Scanner(System.in);
   String str;
   int length;
   System.out.println("Enter String: ");
   str=s.nextLine();
   length=str.length();
   char[] arr;
   arr=str.toCharArray();
   for(int i=length ; i>0 ; i--)
  {
          System.out.print(arr[i]);
  }
    }
    }
  • 2
    array index starts at 0 and goes to size - 1, you need to iterate from `length - 1` to `0`, so change to `for(int i = length - 1; i >= 0; i-- )` – Sam Jun 20 '18 at 17:50
  • if your string has a size of 12 then the max index for that string is going to be 11 (length - 1) because the first index is 0. 0 to 11 is 12 characters total. – RAZ_Muh_Taz Jun 20 '18 at 17:52
  • Or just `System.out.println(new StringBuilder(str).reverse());` – Bohemian Jun 20 '18 at 17:52
  • Hint: you expect others to spend their time to help you with your problem. So you please spend the few seconds it takes to properly format / indent your question. Indentation matters a big deal, and that *preview* window exists for a reason. So that you are able to assess the quality of your input before hitting the submit button. – GhostCat Jun 20 '18 at 18:19

4 Answers4

2

Should be

for(int i=length-1 ; i>=0 ; i--)
Antoniossss
  • 31,590
  • 6
  • 57
  • 99
0

Array indexes are zero-based. This means they go from 0 to the array's length - 1. Your for loop is off by one:

for (int i = length - 1; i >= 0; i--)
{
    System.out.print(arr[i]);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

There are multiple ways of reversing string. https://www.geeksforgeeks.org/reverse-a-string-in-java-5-different-ways/

easiest would be:

    char[] try1 = input.toCharArray(); 
    for (int i = try1.length-1; i>=0; i--)
        System.out.print(try1[i]);

https://ideone.com/e.js/n7j83x

import java.util.Scanner;
class JavaPrograms {
 public static void main(String[] args) {
  Scanner s = new Scanner(System.in);
  String str;
  int length;
  System.out.println("Enter String: ");
  str = s.nextLine();
  length = str.length();
  char[] arr;
  arr = str.toCharArray();
  for (int i = length - 1; i >= 0; i--) {
   System.out.print(arr[i]);
  }
 }
}
Ashu
  • 2,066
  • 3
  • 19
  • 33
0

The easiest way to do this would be

string reversed = new StringBuilder(str).reverse().toString();
System.out.print(reversed);
emsimpson92
  • 1,779
  • 1
  • 9
  • 24