我认为我的语法有问题。所以请帮我解释一下这些语法:
public class Main {
public static void main(String arg[]) {
String number = "1234";
System.out.println("original String: " + number);
String reversed = inPlaceReverse(number);
System.out.println("reversed String: " + reversed);
}
public String inPlaceReverse(final String input) {
final StringBuilder builder = new StringBuilder(input);
int length = builder.length();
for (int i = 0; i < length / 2; i++) {
final char current = builder.charAt(i);
final int otherEnd = length - i - 1;
builder.setCharAt(i, .charAt(otherEnd)); // swap
builder.setCharAt(otherEnd, current);
}
return builder.toString();
}
}
反向功能无法正常工作。
答案 0 :(得分:3)
StringBuilder
具有执行此操作的功能:
StringBuilder.reverse()
您还可以将.toString()附加到此调用以将其恢复为字符串。
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#reverse()
答案 1 :(得分:1)
您的代码中存在一些错误。
1)error: illegal start of expression builder.setCharAt(i, .charAt(otherEnd));
更正:builder.setCharAt(i, **builder**.charAt(otherEnd));
2)error: non-static method inPlaceReverse(String) cannot be referenced from a static context
这是因为你已经将main()声明为静态,而你的isPlaceReverse()是非静态的。您不能在静态成员中引用非静态成员。
将您的功能定义更改为public **static** String inPlaceReverse(final String input)
完成上述更正后,您将获得所需的输出:
public class Main {
public static void main(String args[]) {
String number = "1234";
System.out.println("original String: " + number);
String reversed = inPlaceReverse(number);
System.out.println("reversed String: " + reversed);
}
public static String inPlaceReverse(final String input) {
final StringBuilder builder = new StringBuilder(input);
int length = builder.length();
for (int i = 0; i < length / 2; i++) {
final char current = builder.charAt(i);
final int otherEnd = length - i - 1;
builder.setCharAt(i, builder.charAt(otherEnd)); // swap
builder.setCharAt(otherEnd, current);
}
return builder.toString();
}
}
输出 原始字符串:1234 反向字符串:4321
答案 2 :(得分:0)
将您的反向逻辑更新为:
public static String inPlaceReverse(final String input) {
final StringBuilder builder = new StringBuilder(input);
int length = builder.length();
for (int i = 0; i < length / 2; i++) {
final char current = builder.charAt(i);
final char otherEnd = builder.charAt(length - i - 1);
builder.setCharAt(i, otherEnd); // swap
builder.setCharAt(length-i-1, current);
}
return builder.toString();
}
更合适的方式是:
public static String inPlaceReverse(final String input) { // make it static
final StringBuilder builder = new StringBuilder(input);
return builder.reverse().toString();
}