Why JVM is giving error "incompatible type: String cannot be converted to char" and how to fix it without using other method?

huangapple go评论86阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年8月25日 01:39:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63566048.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定