错误:不兼容的类型:char 无法转换为 String - Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48462019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 10:04:38  来源:igfitidea点击:

error: incompatible types: char cannot be converted to String - Java

java

提问by Titian Cernicova-Dragomir

This is just a part of my code that I have problem troubleshooting.

这只是我的代码的一部分,我有问题故障排除。

static int checkConcat(String number) {
        TreeSet<Integer> a = new TreeSet<Integer>();
        for(int i=0; i<number.length(); i++) {
            a.add(Integer.parseInt(number.charAt(i)));
        }
}

The error that I'm getting is :

我得到的错误是:

error: incompatible types: char cannot be converted to String

错误:不兼容的类型:char 无法转换为 String

What's wrong with the code, and how can I solve it in this context?

代码有什么问题,在这种情况下我该如何解决?

回答by George Z.

You can easily convert the char to String.

您可以轻松地将字符转换为字符串。

char aCharacter = 'c';
String aCharacterAsString = String.valueOf(aCharacter);

So in your case:

所以在你的情况下:

a.add(Integer.parseInt(String.valueOf(number.charAt(i))));

回答by Titian Cernicova-Dragomir

charAtreturns one character of the string, therefore the return type is charnot stringto convert to string use the String.valueOfmethod:

charAt返回字符串的一个字符,因此返回类型char不是string转换为字符串使用String.valueOf方法:

String.valueOf(number.charAt(i))

Or don't use Integer.parsejust subtract '0'from the character to convert it to the digit value. This would be a simpler more efficient way to convert a single digit value.

或者不要Integer.parse只使用'0'从字符中减去将其转换为数字值。这将是转换单个数字值的更简单更有效的方法。

number.charAt(i) -'0'

回答by dasblinkenlight

A single character is char, not String. Although you could construct a single-character string from charusing a method described below, parsing a number digit-by-digit should be done with a different API:

单个字符是char,不是String。虽然您可以char使用下面描述的方法构造一个单字符串,但应该使用不同的 API 逐位解析数字:

for(int i=0; i<number.length(); i++) {
    a.add(Character.digit(number.charAt(i), 10));
}

To construct a single-character string from charin Java, use String.valueOfmethod:

char在 Java 中构造单字符串,请使用String.valueOf方法:

String singleDigit = String.valueOf(number.charAt(i));

回答by dasblinkenlight

Integer.parseInt(String s)has the argument type String, not charas returned by number.charAt(i).

Integer.parseInt(String s)有参数类型String,而不是char通过返回number.charAt(i)

Convert to a String:

转换为String

a.add(Integer.parseInt("" + number.charAt(i)));