为什么我在尝试创建字符串数组时会遇到这两个错误?

时间:2016-02-01 23:23:39

标签: java

String[] wordArray = { “aardvark”, “bat”, “brewers”, “cadmium”, “wolf”, “dastardly”, “enigmatic”, “frenetic”, “sycophant”, “rattle”, “zinc”, “alloy”, “tunnel”, “nitrate”, “sample”, “yellow”, “mauve”, “abbey”, “thinker”, “junk"};

我收到了错误:

 Multiple markers at this line
    - Syntax error on token(s), misplaced 
     construct(s)
    - String literal is not properly closed by a 
     double-quote

2 个答案:

答案 0 :(得分:1)

尝试使用标准双引号"",如:

  String[] wordArray = { "aardvark", "bat", "brewers",...

答案 1 :(得分:0)

当您从文档或网站复制代码时,这是常见问题。

在Java中,我们通过以"字符结束它们来创建字符串文字,但许多文档编辑使用来创建引号,这些引号不被认为是正确的字符串标记的起始端。

您可以尝试使用此辅助方法生成正确的代码:

public static String fixQuotes(String text){
    return text.replaceAll("“|”", "\""); //replace “ OR ” with " (we need to escape `"` 
                                         //with \ to make compiler treat " as literal and 
                                         //not end of string
}

用法:

System.out.println(fixQuotes("String[] wordArray = { “aardvark”, “bat”, “brewers”, “cadmium”, “wolf”, “dastardly”, “enigmatic”, “frenetic”, “sycophant”, “rattle”, “zinc”, “alloy”, “tunnel”, “nitrate”, “sample”, “yellow”, “mauve”, “abbey”, “thinker”, “junk\"};"));

将打印您以后可以使用的代码。

String[] wordArray = { "aardvark", "bat", "brewers", "cadmium", "wolf", "dastardly", "enigmatic", "frenetic", "sycophant", "rattle", "zinc", "alloy", "tunnel", "nitrate", "sample", "yellow", "mauve", "abbey", "thinker", "junk"};

但要小心,因为此方法会将所有替换为",而不仅仅是那些您打算成为字符串开头和结尾的那些。