I am having a slight issue with my String Reverse code, and I cannot seem to fix it. I have made a different way that works, involving a for-loop, and that seems to work fine. However, when I run this code, it always gives me a "null" before the reversed String. For example, when I run this and input "StackOverflow", I get an output of null wolfrevOkcatS" (without the Space). I do not understand why an error like this would happen, so I also added a "null" checker, which did not seem to work. For this null checker, I converted the char into an Ascii value before putting it into my reversed string, and then checked if it was 0. (The ascii value of null) However, this did not seem to work, so I did some research, and could not find anything on Overflow, so decided to ask this question. Sorry and apologies in advance if this is a very "dumb" question, as I am quite new to java, and do not know who to ask.
Thanks in advance,
- A novice Java Coder
import java.util.Scanner;
public class StringReverser
{
static String input, reversed;
int i;
public static void main(String[] args)
{
StringReverser ansh = new StringReverser();
ansh.grab();
ansh.reverse(input);
}
public void grab()
{
System.out.println("Enter a word to be reversed: ");
Scanner kys = new Scanner(System.in);
input = kys.next();
i = input.length();
}
public void reverse(String word)
{
if(i == 0)
{
System.out.println(reversed);
}
else
{
//if((int)(word.charAt(i-1)) == 0)
//{i--; reverse(input);}
reversed+=word.charAt(i-1);
i--; reverse(input);
}
}
}