-3

Trying to reverse the string input.

Eg: input- hello friend output- dneirf olleh

Here is the program I made but it shows string index out of range as error:

import java.io.*;
class Worksheet3sum3
{
    public static void main(String args[])throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int i;
        System.out.print("enter string ");
        String S=br.readLine();
        String y=" ";
        for(i=0;i<=S.length();i++)
        {
            char ch=S.charAt(i);
            y=ch+y;
        }
        System.out.print("the reverse is "+y);
    }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
Pranjal
  • 1
  • 1

2 Answers2

0

Using substrings, you can loop through the string that you want to print out backwards, and print out the characters of the string backwards like that.

You can also use the command .toCharArray(), and loop through the character array backwards to print out the word backwards.

Lavaman65
  • 863
  • 1
  • 12
  • 22
0

The reason why it's saying index out of bounds is because you're going beyond the last index of the string, remember we always start counting at 0, so in this case, you meant to say
i < S.length().

for(i=0;i<=S.length();i++) // this is why it's saying index out of bounds because you're going 1 index beyond the last.
{
    char ch=S.charAt(i);
    y=ch+y;
}

The below solution should solve your "IndexOutOfBounds" problem:

 for(i=0;i< S.length();i++) // notice the  "i < S.length() "
 {
    char ch=S.charAt(i);
    y=ch+y;
 }

Also, I would like to provide a simple and easy algorithm which you can use to achieve the same result.

 public static void main(String[] args) {
     Scanner scanner = new Scanner(System.in);
     System.out.println("enter string ");
     String value = scanner.nextLine(); 
     StringBuilder builder = new StringBuilder(value); // mutable string
     System.out.println("reversed value: " + builder.reverse()); // output result
  }

UPDATE

As you have asked me to expand on the issue of why you're getting IndexOutOfBounds error I will provide a demonstration below.

lets assume we have a variable String var = "Hello"; now as you can see there are 5 characters within the variable, however, we start counting at 0, not 1 so "H" is index 0, "e" is index 1, "l" index 2 and so forth, eventually if you want to access the last element it's index 4 even though we have 5 characters within the string variable. So referring to your question the reason why it says index of out bounds is because you're going 1 index above the last. here is a link for further explanation and exercises on the issue.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126