简体   繁体   English

赋值的左侧必须是变量错误

[英]The Left Hand Side Of an assignment must Be A Variable Error

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);

    }

}

I wanted to switch the first Letter and the last letter of a word but I get this error The Left Hand Side Of An Assignment Must Be A Variable The error is in the X.charAt(0) = x.charAt(x.length) x.charAt(x.length()) = temp;我想切换单词的第一个字母和最后一个字母,但出现此错误The Left Hand Side Of An Assignment Must Be A Variable The error is in the X.charAt(0) = x.charAt(x.length) x.charAt(x.length()) = temp; Sorry if it's a dumb question I'm kind of new to programming.对不起,如果这是一个愚蠢的问题,我对编程有点陌生。

x.charAt(0) or x.charAt(x.length()) is not a variable, it just return a value. x.charAt(0)x.charAt(x.length())不是变量,它只是返回一个值。 For assigning a value left hand side must be a variable.对于赋值左侧必须是一个变量。 String object is immutable.字符串 object 是不可变的。 You can use StringBuilder or create char array then swap.您可以使用 StringBuilder 或创建 char 数组然后交换。

char arr[] = x.toCharArray();
char tmp = arr[x.length-1];
arr[x.length-1] = arr[0];
arr[0] = tmp;

As the other answer said, x.charAt(0) is not a variable.正如另一个答案所说, x.charAt(0)不是变量。

So doing:这样做:

x.charAt(0) = x.charAt(x.length()-1);

would not work.行不通。

In Java Strings are not changeable.在 Java 中,字符串不可更改。 So if you really want to write an algorithm that needs to modify characters of a string in-place I'd suggest using StringBuilder:因此,如果您真的想编写一个需要就地修改字符串字符的算法,我建议使用 StringBuilder:

StringBuilder sb = new StringBuilder(x);
sb.setCharAt(0, x.charAt(x.length()-1));

Note: x.charAt(x.length()) is beyond the end of the String since indices start with 0. So that's why I added a -1.注意: x.charAt(x.length())超出了字符串的末尾,因为索引从 0 开始。这就是我添加 -1 的原因。

When you're done editing your StringBuilder you can convert it back to a String like this:完成编辑StringBuilder后,您可以将其转换回 String ,如下所示:

result = sb.toString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM