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;
    }
Jeremy Sawyer
  • 83
  • 1
  • 6

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
  • 17,677
  • 1
  • 23
  • 51
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
  • 13,064
  • 15
  • 63
  • 112
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,372
  • 1
  • 12
  • 19
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
  • 716
  • 1
  • 11
  • 20