newer programmer here, having trouble diagnosing the issue with my string reversal program. The program is supposed to compare two strings and find out if string x is the reversal of string y and if it is it returns true, if not it returns false.
public class Reverse
{
public static void main(String[] args)
{
System.out.println(isExactReverse("ba", "a"));
System.out.println(isExactReverse("desserts", "stressed"));
System.out.println(isExactReverse("apple", "apple"));
System.out.println(isExactReverse("regal", "lager"));
System.out.println(isExactReverse("war", "raw"));
System.out.println(isExactReverse("pal", "slap"));
}
public static boolean isExactReverse(String x, String y)
{
//To be completed
int counter = 0;
int temp = x.length() - 1;
boolean result = false;
for(int i = 0; i < y.length(); i++)
{
if(x.charAt(temp) == y.charAt(i))
{
counter++;
}
temp--;
}
if(counter == y.length())
{
result = true;
}
return result;
}
}
the output i get is not correct and I am getting a runtime error.
true
true
false
true
true
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.charAt(String.java:658)
at Reverse.isExactReverse(Reverse.java:24)
at Reverse.main(Reverse.java:11)
Expected output:
False
True
False
True
True
False