0

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?

1
  • you are starting you for loop with an index value of i = 1 instead of i = 0 Commented Mar 25, 2015 at 16:09

4 Answers 4

7

But the actual output was

[...]

Not with the code you posted. The code you posted wouldn't compile, because:

  • You didn't end the field initialization with a semi-colon
  • If you had, you'd be trying to access an instance field without creating an instance
  • After fixing that, you'd have run into an 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.)

Sign up to request clarification or add additional context in comments.

Comments

1

Errors are as follows:-

1.As you have initialized your words array with argument starting from 0 so you have to start your for loop from 0.

2.There are minor errors in your question as well reagrding declaring words as static and semicolon error which i have edited already in your question.

here is your code working properly:-

 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);
 }
 }

Comments

1

Your index on the loop must start with 0 for int i=0; ....., as arrays in java start at position 0 and end at length-1

Comments

1

Your loop should be like this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.