-1

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 :).

user547075
  • 53
  • 1
  • 8

1 Answers1

2

Just add a check for null at the start and set str to a String of null:

public static String reverse (String str){  
      //New code
      if (str == null) {
           str = "null";
      }

      String reverse = "";
      for(int i = str.length() - 1; i >= 0; i--){
          reverse += str.charAt(i);
      }
      return reverse;
 }

Output when null:

llun

You can also just hard code the case as return "llun"; of course as well so it does not actually go into the loop or return null; if you want to return null itself and not reverse it:

if (str == null) {
    return "llun";
    //return null; //If you want to just return null instead
} 
Nexevis
  • 4,647
  • 3
  • 13
  • 22