I have this problem that I have to reverse the order of a string that appears.
I've tried reversing the string by creating an empty string, then adding the characters from the back using a for loop.
However, it doesn't really work with the null. Below is the code I tried.
public static String reverse (String str){
String reverse= "";
for(int i=str.length()-1; i>=0; i--){
reverse+=str.charAt(i);
}
return reverse;
}
This is the tester.
String s1=null;
System.out.println (reverse(s1));//null
System.out.println (reverse(""));// empty string
System.out.println (reverse("a"));//a
System.out.println (reverse("abc"));//cba
System.out.println (reverse("atoyota"));// atoyota
System.out.println (reverse("atOyotA"));//AtoyOta
System.out.println (reverse("dad"));//dad
System.out.println (reverse("Dad"));// daD
System.out.println (reverse("DaD"));// DaD
The error I get from doing the code above is
Exception in thread "main" java.lang.NullPointerException
at PalindromeLab_BB.reverse(PalindromeLab_BB.java:62)
at PalindromeLab_BB.main(PalindromeLab_BB.java:5)
Anyone got any idea what's wrong, or how to fix it?
Any help would be greatly appreciated :).