0

Sorry to bother you all but I'm new two programming and I'm really stuck on this task. I have to add code to the class to print numbers from this array in order to make a for-loop.

This is what I have so far:

public class ArrayExercise
{
  public static void main(String[] args)
  {
    String[] numbers = {"one", "two", "three", "four", "five"};
    String numbers = number[i];
    String nextnumber = number[i + 1];
  }
}

How can I do this?

ylun.ca
  • 2,504
  • 7
  • 26
  • 47
  • 2
    Have you read Oracle's tutorial on [for loops](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html)? – PakkuDon Feb 16 '14 at 01:59
  • 1
    var numbers is String[] or String !? String[] numbers = {"one", "two", "three", "four", "five"}; String numbers = number[i]; – Zied R. Feb 16 '14 at 02:01

2 Answers2

2

A for loop is used as follows:

for( *variable used as an index*; *condition*; *index variable change*){
*loop body*
}

In your case, I would do something along the lines of:

for(int i = 0; i < numbers.length; i++){
    System.out.println(numbers[i]);
}

(Note that i < 5 because array value positions start a 0 and go to [Array Size]-1)

The strings numbers and nextnumber in your code is unnecessary.

So your program should look like this:

public class ArrayExercise
{
  public static void main(String[] args)
  {
    String[] numbers = {"one", "two", "three", "four", "five"};

    for(int i = 0; i < numbers.length; i++){
        System.out.println(numbers[i]);
    }
  }
}
ylun.ca
  • 2,504
  • 7
  • 26
  • 47
  • 1
    Rather than using a magic number in the loop condition (`5`), you should use `< numbers.length` – Brian Roach Feb 16 '14 at 02:09
  • 2
    arrays are *never* variable length; they're fixed size. And they are defined elsewhere in the code and could be changed later ... which is *why* you avoid magic numbers in conditionals like that. Otherwise you'd have to remember to update the loop as well when changing the array. – Brian Roach Feb 16 '14 at 02:12
  • So if OP or somebody else adds a new item in the array e.g. `"six"`, save the file, recompiles it and runs, the application should only print from `"one"` to `"five"`? – Luiggi Mendoza Feb 16 '14 at 02:12
2

One option is you can do it like this

public class ArrayExercise
{
    public static void main(String[] args)
    {
        String[] numbers = {"one", "two", "three", "four", "five"};
        for (int i = 0; i < numbers.length; i++)
        {
            System.out.println(numbers[i])
        }
    }
}

or, you can do it like this.

public class ArrayExercise
{
    public static void main(String[] args)
    {
        String[] numbers = {"one", "two", "three", "four", "five"};
        for (String number:numbers)
        {
            System.out.println(number)
        }
    }
}
TheOneWhoPrograms
  • 629
  • 1
  • 8
  • 19