I made an array of Strings with following code
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);
}
}
What I expected to receive as output was:
"Watch on youtube : Mickey en de stomende drol"
But the actual output was
"on youtube : Mickey en de stomende drol"
I think I made a little mistake, how does it come?
But the actual output was
[...]
Not with the code you posted. The code you posted wouldn't compile, because:
ArrayIndexOutOfBoundsException
for basically the same reason as you missed out the first element - see below.This:
for(int i = 1 ; i <= words.length ; i++)
Should be:
for (int i = 0; i < words.length; i++)
Note that both the start index and the loop condition have changed. The latter is the idiomatic way of expressing a loop from 0 (inclusive) to an exclusive upper bound.
Arrays in Java are 0-based - so for example, an array with length 4 has valid indexes of 0, 1, 2 and 3. See the Java arrays tutorial for more details.
(As an aside, repeated string concatenation like this is generally a bad idea. It's not a problem in your case as there are so few values, but you should learn about StringBuilder
.)
See more on this question at Stackoverflow