Apparent issues with initializing arrays of strings in Java.

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

Apparent issues with initialsing arrays of strings in Java

问题

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

  1. Java中,声明和初始化字符串数组时遇到了问题。对于为什么会发生这种情况感到困惑,因此从Grails Cookbook中复制了一段示例代码,但似乎也不起作用?
  2. ```java
  3. public class StringArray {
  4. String[] testArray = new String[5];
  5. testArray[0] = "Daddy";
  6. testArray[1] = "Mommy";
  7. testArray[2] = "Brother";
  8. testArray[3] = "Sister";
  9. testArray[4] = "Dog";
  10. }

错误消息示例:

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

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

  1. 请注意,我已经删除了不需要的部分,只提供了翻译的内容。
  2. <details>
  3. <summary>英文:</summary>
  4. [1]: https://i.stack.imgur.com/Y4esB.png
  5. 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";
}

  1. sample of error messages

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

  1. 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.
  2. </details>
  3. # 答案1
  4. **得分**: 3
  5. 初始化数组的语句需要放置在方法或构造函数的主体中。你提到的示例可能假定整个代码都在一个方法中。
  6. 在你的情况下,这种一行初始化的方式仍然有效:
  7. ```java
  8. public class StringArray{
  9. String[] testArray = {"Daddy", "Mommy", "Brother", "Sister", "Dog"};
  10. }
英文:

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:

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

答案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:

确定