字符错误 "char cannot be converted to string"

charAt error "char cannot be converted to string"

我正在尝试使用以下代码,以便给定一个字符串,给出相同字符的最长连续子序列的长度。我收到错误 "incompatible types: char cannot be converted to java.lang.String"。我在下面评论了发现错误的地方。

public class Test {
    public int longestRep(String str)
    {
        int currLen = 1;
        String currLet = "";
        String maxLet = "";
        int maxCount = 0;
        int currPos = 0;
        int strLen = str.length();
        for(currPos = 0; currPos < strLen; currPos++)
        {
            currLet = str.charAt(currPos); //error is on this line
            if(currLet = str.charAt(currPos+1))
            {
                currLen++;
            }
            else
            {
                if(currLen > maxLen)
                {
                    maxLen = currLen;
                    maxLet = currLet;
                    currLen = 1;
                }
            }
        }
    }
    public static void main(String args[])
    {
        longestRep("AaaaMmm");
    }
}

String.charAt(int)returns一个字符。但是currLetString类型的,所以不能给字符赋值。请改用 currLet = Character.toString(str.charAt(currPos));

  • currLet = str.charAt(currPos); String 值不能分配给 char,它们是不同的类型,苹果和橙子
  • if (currLet = str.charAt(currPos + 1)) {其实就是一个赋值(让currLet等于str.charAt(currPos + 1)的值)
  • if (currLen > maxLen) { - maxLen 未定义
  • 你永远不会return方法中的任何东西...

尝试更改:

  • String currLet = ""; 更像是 char currLet = '[=20=]';String maxLet = ""; 更像是 char maxLet = '[=22=]';
  • if (currLet = str.charAt(currPos + 1)) {if (currLet == str.charAt(currPos + 1)) {
  • int maxLen = 0 添加到您的变量 declerations(可能在 int maxCount = 0 下)

现在,根据您的示例代码,public int longestRep(String str) { 需要 public static int longestRep(String str) { 才能让您调用 main 方法...

正如编译器所说,您无法将 char 转换为 String。如果你有一个 char 并且你真的想将它转换为长度为 1 的 String,这将起作用:

String s = String.valueOf(c);

String s = Character.toString(c);

然而,如果你正在使用的角色是由charAt获得的,另一种解决方案是去掉charAt并使用substring到return长度为 1 的字符串:

currLet = str.substring(currPos, currPos + 1);

将 Char 转换为 String 的简单方法

在表达式的开头添加一个空字符串,因为将 char 和 String 添加到 String 中。

转换一个字符 "" + 'a'
转换多个字符 "" + 'a' + 'b'

转换多个字符有效,因为 "" + 'a' 首先计算。
如果 "" 在最后,你会得到 "195"

Remember that Java language guarantees (Java Language Specification, Java SE 7 Edition, section 15.12.4.2) that all arguments are evaluated from left to right (unlike some other languages, where the order of evaluation is undefined)