import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char temp;
char temp2;
System.out.println("Enter Word");
String x = in.next();
System.out.println("Your Word has " + x.length()+ " Letters" + "\n");
int[] array = new int[x.length()];
for(int i = 0; i < array.length; i++){
array[i] = x.charAt(i);
}
temp = x.charAt(0);
**x.charAt(0) = x.charAt(x.length);
x.charAt(x.length()) = temp;**
System.out.println(x);
}
}
我想切换单词的第一个字母和最后一个字母,但出现此错误
The Left Hand Side Of An Assignment Must Be A Variable
错误出现在X.charAt(0) = x.charAt(x.length) x.charAt(x.length()) = temp;
抱歉,这是一个愚蠢的问题,我是编程新手。
最佳答案
正如另一个答案所说,x.charAt(0)不是变量。
这样做:
x.charAt(0) = x.charAt(x.length()-1);
将无法正常工作。
在Java中,字符串不可更改。因此,如果您真的想编写一种需要就地修改字符串字符的算法,则建议使用StringBuilder:
StringBuilder sb = new StringBuilder(x);
sb.setCharAt(0, x.charAt(x.length()-1));
注意:x.charAt(x.length())超出了字符串的末尾,因为索引从0开始。所以这就是为什么我添加-1的原因。
完成StringBuilder的编辑后,您可以将其转换回如下所示的String:
result = sb.toString();