1

I am trying to use a method to reverse the characters in a string and I keep getting a type mismatch error. Any thoughts?

public static String userReverse (String userEntry3) {
    String reverse = "";    
       for (int i = (userEntry3.length() -1); i >= 0 ; i--) {
       reverse = System.out.println(userEntry3.charAt(i));
    }
    return reverse;
    }

4 Answers4

2

System.out.println is a void method. It returns nothing. So it cannot assigned back to a String variable

Your code is wrong.

If you want to reverse a string, you can use this:

public static String userReverse (String userEntry3) {
    return new StringBuilder(userEntry3).reverse().toString()
}
Mạnh Quyết Nguyễn
  • 15,590
  • 1
  • 17
  • 41
0

Get rid of System.out.println and add a += to concatenate the new char

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

EDIT: As Tim said in the comments, StringBuilder can be used too (and is better practice than concatenating strings in a loop):

public static String userReverse (String userEntry3) {
    StringBuilder reverse = new StringBuilder();    
    for (int i = (userEntry3.length() -1); i >= 0 ; i--) {
        reverse.append(userEntry3.charAt(i));
    }
    return reverse.toString();
}
ryvantage
  • 11,982
  • 13
  • 54
  • 98
  • Still there is no explanation, why `StringBuilder` is better and what is wrong with `System.out.println()` Poor programming(er) instance. – snr Jun 17 '18 at 05:00
0

A more optimized way to reverse a string includes two pointer approach: Use one pointer to start from the beginning and the other to start from the end. By the time they meet each other your string is already reversed

public static String userReverse (String userEntry3) {

    int i = 0;
    int j = userEntry3.length()-1;
    StringBuilder myName = new StringBuilder(userEntry3);

    for(; i < j ; i++,j--){
        char temp = userEntry3.charAt(i);
        myName.setCharAt(i,userEntry3.charAt(j));
        myName.setCharAt(j,temp);
    }
    return myName.toString();

}
Yati Sawhney
  • 1,334
  • 1
  • 11
  • 18
0

System.out.println() is a void method and it not return anything. you should try it this way,

public static String userReverse (String userEntry3) {
String reverse = "";    
  for (int i = (userEntry3.length() -1); i >= 0 ; i--) {
   reverse += userEntry3.charAt(i).toString();
}
return reverse;
}
Yohan Malshika
  • 415
  • 6
  • 17