英文:
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'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 = {"Daddy", "Mommy", "Brother", "Sister", "Dog"};
}
答案2
得分: -1
Include public static void main(String[] args){//code} following the class header.
Here is an example:
The output: Daddy, Mommy, Brother, Sister, Dog,
英文:
Include public static void main(String[] args){//code} following the class header.
Here is an example:
The output: Daddy, Mommy, Brother, Sister, Dog,
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论