带有字符串数组的意外输出

Unexpected output with array of Strings

我用下面的代码制作了一个字符串数组

public class Main 
{
    static String[] words = {"watch", "on", "youtube",":","Mickey","en","de","stomende","drol"};
    public static void main(String[] args)
    {
        String output = "";
        for(int i = 1 ; i <= words.length ; i++)
        {
            output += " " + words[i];
        }

        System.out.println(output);
    }
}

我期望收到的输出是:

"Watch on youtube : Mickey en de stomende drol"

但实际输出是

"on youtube : Mickey en de stomende drol"

我觉得我犯了一个小错误,怎么来的?

循环中的索引必须从 0 for int i=0; ..... 开始,因为 java 中的数组从位置 0 开始,到长度 1

结束

你的循环应该是这样的

for(int i=0; i<words.length; i++)

But the actual output was

[...]

不适用于您发布的代码。您发布的代码无法编译,因为:

  • 您没有以分号结束字段初始化
  • 如果有,您将尝试在不创建实例的情况下访问 实例 字段
  • 修复该问题后,您将 运行 变成 ArrayIndexOutOfBoundsException,原因与您错过第一个元素的原因基本相同 - 见下文。

这个:

for(int i = 1 ; i <= words.length ; i++)

应该是:

for (int i = 0; i < words.length; i++)

请注意,起始索引 循环条件都已更改。后者是表达从 0(含)到独占上限的循环的惯用方式。

Java 中的数组是从 0 开始的 - 例如,长度为 4 的数组的有效索引为 0、1、2 和 3。有关详细信息,请参阅 Java arrays tutorial

(顺便说一句,像这样重复的字符串连接通常不是一个好主意。在你的情况下这不是问题,因为值太少了,但你应该了解 StringBuilder。)

错误如下:-

1.As 你已经用从 0 开始的参数初始化了你的 words 数组,所以你必须从 0 开始你的 for 循环。

2.There 是您问题中的小错误以及重新声明单词为静态和分号错误,我已经在您的问题中进行了编辑。

您的代码可以正常工作:-

 public class Main {

 static String[] words =  {"watch", "on", "youtube",":","Mickey","en","de","stomende","drol"};
 public static void main(String[] args){
 String output = "";

 for(int i = 0 ; i <= words.length-1 ; i++)
 {
    output += " " + words[i];
 }

 System.out.println(output);
 }
 }