Apparent issues with initializing arrays of strings in Java.

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

Apparent issues with initialsing arrays of strings in Java

问题

I've translated the provided text into Chinese for you:

在Java中,声明和初始化字符串数组时遇到了问题。对于为什么会发生这种情况感到困惑,因此从Grails Cookbook中复制了一段示例代码,但似乎也不起作用?

```java
public class StringArray {
    String[] testArray = new String[5];

    testArray[0] = "Daddy";
    testArray[1] = "Mommy";
    testArray[2] = "Brother";
    testArray[3] = "Sister";
    testArray[4] = "Dog";
}

错误消息示例:

C:\Users\aejmu\Desktop\MSc_CIS\javaLabs>javac StringArray.java
StringArray.java:5: error: ']' expected
testArray[0] = "Daddy";
          ^

我在sublime中包含了代码的屏幕截图。我确信这里有一个显而易见的原因,但是我无法找出来。


请注意,我已经删除了不需要的部分,只提供了翻译的内容。

<details>
<summary>英文:</summary>

 [1]: https://i.stack.imgur.com/Y4esB.png

Having trouble declaring and then initialising an array of strings in java. Was confused as to why it was happening so copied a peice of example code from Grails Cookbook and that doesnt seem to work either? 

public class StringArray{
String[] testArray = new String[5];

testArray[0] = "Daddy";
testArray1 = "Mommy";
testArray[2] = "Brother";
testArray[3] = "Sister";
testArray[4] = "Dog";
}

sample of error messages

C:\Users\aejmu\Desktop\MSc_CIS\javaLabs>javac StringArray.java
StringArray.java:5: error: ']' expected
testArray[0] = "Daddy";
^

included a screenshot of the code in sublime. Im sure there&#39;s an obvious reason for this but i cant for the life me figure it out.

</details>


# 答案1
**得分**: 3

初始化数组的语句需要放置在方法或构造函数的主体中。你提到的示例可能假定整个代码都在一个方法中。

在你的情况下,这种一行初始化的方式仍然有效:

```java
public class StringArray{
    String[] testArray = {"Daddy", "Mommy", "Brother", "Sister", "Dog"};
}
英文:

The statements that initialize the array need to be placed in the body of a method or constructor. The example you took probably assumes the entire code is within a method.

The one-line initialization way still works in your case:

public class StringArray{
    String[] testArray = {&quot;Daddy&quot;, &quot;Mommy&quot;, &quot;Brother&quot;, &quot;Sister&quot;, &quot;Dog&quot;};
}

答案2

得分: -1

Include public static void main(String[] args){//code} following the class header.
Here is an example:

Code

The output: Daddy, Mommy, Brother, Sister, Dog,

英文:

Include public static void main(String[] args){//code} following the class header.
Here is an example:

Code

The output: Daddy, Mommy, Brother, Sister, Dog,

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

发表评论

匿名网友

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

确定