首页 > 解决方案 > 为什么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";等等。我想知道错误在哪里以及如何修复此代码,因为我在一本书上找到了此代码,所以我想确认这是打印错误还是什么。

标签: java

解决方案


您正在尝试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);

推荐阅读