[英]Reverse String Method type mismatch error java
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;
}
System.out.println
is a void method. System.out.println
是一个无效方法。 It returns nothing. 它什么也不返回。 So it cannot assigned back to a
String
variable 因此无法将其分配回
String
变量
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()
}
Get rid of System.out.println
and add a +=
to concatenate the new char 摆脱
System.out.println
并添加+=
以连接新字符
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): 编辑:正如蒂姆在评论中所说,
StringBuilder
也可以使用(比在循环中连接字符串更好的做法):
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();
}
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();
}
System.out.println() is a void method and it not return anything. System.out.println()是一个无效方法,它不返回任何内容。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.