英文:
Why JVM is giving error "incompatible type: String cannot be converted to char" and how to fix it without using other method?
问题
public class Test2 {
public static void main(String arga[]) {
char arr[] = {'T','h','i','s',' ','i','s',' ','a',' ','t','e','s','t'};
String str = new String(arr);
System.out.println(str);
}
}
Output:
This is a test
错误出现在代码的这一行:
char arr[] = {"T","h","i","s"," ","i","s"," ","a"," ","t","e","s","t"};
这里试图用字符串字面量来初始化字符数组,然而字符数组应该使用单引号来表示字符,而不是双引号。正确的做法是使用单引号:
char arr[] = {'T','h','i','s',' ','i','s',' ','a',' ','t','e','s','t'};
这将会把字符数组初始化为包含指定字符的序列,之后就可以用这个字符数组创建一个字符串。
英文:
Code:
public class Test2 {
public static void main(String arga[]) {
char arr[] = {"T","h","i","s"," ","i","s"," ","a"," ","t","e","s","t"};
String str = new String(arr);
System.out.println(str);
}
}
Output:
Test2.java:5: error: incompatible types: String cannot be converted to char
char arr[] = {"T","h","i","s"," ","i","s"," ","a"," ","t","e","s","t"};
^
Where's the error in the above code and how to fix it? please dont recommend me to use other method like: String str = "This is a test";
etc etc. I want to know where's the error and how to fix this code, because I found this code on a book so I want to confirm if this is a printing mistake or something.
答案1
得分: 2
你正在尝试创建一个包含字符串的char
数组。以下是正确的语法:
char arr[] = new char[]{'T','h','i','s',' ','i','s',' ','a',' ','t','e','s','t'};
String str = new String(arr);
System.out.println(str);
英文:
You are trying to create a char
array with Strings. Here is the right syntax:
char arr[] = new char[]{'T','h','i','s',' ','i','s',' ','a',' ','t','e','s','t'};
String str = new String(arr);
System.out.println(str);
答案2
得分: 0
你正在使用字符串双引号 "
。在处理字符时,您应该使用单引号 '
。
英文:
You are using string double quotes "
. You want to use a single quote '
when working with chars.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论