简体   繁体   English

Java:参数的左侧必须是变量charAt错误

[英]Java: Left-hand side of an argument must be a variable charAt error

I am replacing all vowels in a String with a char using a for loop. 我使用for循环用char替换了字符串中的所有元音。

public String replaceVowel(String text, char letter)
{
    char ch;
    for(int i = 0; i<text.length(); i++)
    {
        ch = text.charAt(i);
        if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y')
        {
            ch = letter;
        }   
        text.charAt(i) = ch;
    }
    return text;
}

The code trips on an error on line: 代码因错误而跳闸:

text.charAt(i) = ch;

In this line I am attempting to initialize the char at the loop's location of the string. 在这一行中,我尝试在字符串的循环位置处初始化char。 However the line produces the error: 但是,该行会产生错误:

The left-hand side of an assignment must be a variable 作业的左侧必须是变量

Any help is appreciated! 任何帮助表示赞赏!

As oppsed to C++, Java method call never return a variable "reference" (like C++ reference) so you can never assign a method call result. 与C ++一样,Java方法调用从不返回变量“引用”(例如C ++引用),因此您永远无法分配方法调用结果。

Also Java string is immutable, which means you cannot change individual characters in a string without creating a new string. Java字符串也是不可变的,这意味着您不能在不创建新字符串的情况下更改字符串中的各个字符。 See this post Replace a character at a specific index in a string? 看到这篇文章替换字符串中特定索引处的字符? on this topic. 关于这个话题。

charAt(index) returns the character in that index. charAt(index)返回该索引中的字符。 It cannot be used for assigning values. 它不能用于分配值。

Something like this would work: 这样的事情会起作用:

char ch;
        String text = "hailey";
        char letter = 't';
        char[] textAsChar = text.toCharArray();
        for(int i = 0; i<text.length(); i++)
        {
            ch = text.charAt(i);
            if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y')
            {
                ch = letter;
            }   
            textAsChar[i] = ch;
        }
        System.out.println(String.valueOf(textAsChar));

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

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