java - 为什么JVM给出错误“不兼容的类型:字符串无法转换为char”以及如何在不使用其他方法的情况下修复它?
问题描述
代码:
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);
}
}
输出:
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"};
^
上述代码中的错误在哪里以及如何解决?请不要推荐我使用其他方法,例如:String str = "This is a test";
等等。我想知道错误在哪里以及如何修复此代码,因为我在一本书上找到了此代码,所以我想确认这是打印错误还是什么。
解决方案
您正在尝试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);
推荐阅读
- angularjs - 有没有办法检测应用程序何时从空闲或 Ionic v1 中的主按钮打开?
- jsp - 循环在primefaces DataTable中制作动态列
- apache-kafka - 如何避免在 Kafka 流中创建更改日志?
- php - 使用 Bootstrap 4、PHP、MySQLi 和 Ajax 无法进行实时搜索
- android - 为什么在搜索框中输入任何内容时不显示项目?
- json - JSON 文件中的 Ansible 变量替换问题
- excel - 使用 lastrow 的多柱形图 - 1
- react-native - React-Native:如何在应用程序关闭之前保存数据
- javascript - 使用 Stripe Connect PHP 添加外部银行账户不起作用 空白页
- javascript - 模态文本区域不会从单击它的按钮加载数据属性