-1

I'm working on an assignment for one of my classes. I'm very new to java in general and for this problem I was asked to only use loops and the charAt(); command to reverse the midpoint of a string. However, I came to an issue when I try to reverse the string after the midpoint. It gave me an exception and I don't know how to make of it since it looks correct to me. Any help would be appreciated.

import java.util.Scanner;
public class PS4Reverse {

public static void main (String [] args) {

String x = "";

String t = "";

String full = "";

String rev = "";

String complete = "";

Scanner user = new Scanner(System.in);
System.out.println("Enter a string.");
x = user.nextLine();

int real = x.length();

int half = x.length();

half = half / 2;

int i = 0;


for (i = 0; i != half; i++)
{
    char n = x.charAt(i);
    full = full + n;

}


for (i = i; i != real; i++)
{
    char n = x.charAt(i);
    t = t + n;
}

int back = t.length();


System.out.println(back);
for (i = back; i != 0; i--)
{
    char n = t.charAt(i);
    rev = rev + n;
}


complete = full + rev;

System.out.println("Original String:\t\t" + x)
System.out.println("Reverse String:\t\t" + complete);


}
}

Thank all y'all very much in advance!

2 Answers2

1

First of all, it helps if you're exact when telling us what exception is happening. It is a StringIndexOutOfBoundsException, not a String out of Range exception or an indexoutofrangeexception.

Anyway, this is the issue:

int back = t.length();

for (i = back; i != 0; i--)
{
    char n = t.charAt(i);

The indexes are zero-baed, so if t.length() is 4, t.charAt(4) is going to be out of bounds. You need to start at t.length() - 1.

D M
  • 1,410
  • 1
  • 8
  • 12
  • You're also missing a semicolon after one of your `System.out.println()` statements, but I assume that's just a typo. – D M Mar 14 '17 at 05:31
0

You got this error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
    at java.lang.String.charAt(Unknown Source)
    at PS4Reverse.main(PS4Reverse.java:49)


int back = t.length(); // this code length of t string. But array indis is starting 0. 

This means first item is 0 , last item must be back-1.

you use that;

for (i = back-1; i >= 0; i--)
{
    char n = t.charAt(i);
    rev = rev + n;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • This worked for me.. Thank you so much. I greatly appreciate it! – Gavin Webb Mar 14 '17 at 05:35
  • @GavinWebb [Here](http://stackoverflow.com/help/someone-answers) is what to do when someone answers your question. To mark an answer as accepted, click on the check mark ✔ beside the answer to toggle it from greyed out to filled in. There is no need to add a comment on your question or on an answer to say "Thank you". – Patrick Parker Mar 14 '17 at 17:43