-2

Hello I'm trying to get my array "numbers" to print out all even numbers for some reason I can't get it to call the array from earlier in my code so that the array can be used down below.

 import java.util.Random;

public class Main {
  public static void main(String [] args){
      int numbers[] = new int [10];
      for (int x = 0; x < numbers.length; x++){
      Random rand = new Random();
      numbers[x] = rand.nextInt(100)+1;
      System.out.print("" + numbers[x] + " ");
      }
    System.out.println("");
    System.out.print("The values at even indexes are: " + numbers[0] + " " + numbers[2] + " " + numbers[4] + " " + numbers[6] + " " + numbers[8]);
    System.out.println("");
    if(numbers[x] % 2 == 0){
      System.out.print(numbers[x]);
    }
  }
}
vlaxmi
  • 468
  • 4
  • 18
Matthew M
  • 3
  • 2
  • 4
    Arrays don't get "called". You simply need to re-loop through the array in another for loop. – Hovercraft Full Of Eels Mar 29 '17 at 00:53
  • 1
    You can't use `x` outside the for loop. It is out of scope. You probably want this inside a loop anyway, to print all the even values, so you just need to wrap this inside a new for loop with `x` as the iterator. – RaminS Mar 29 '17 at 00:53
  • Possible duplicate of [How to find index of int array in Java from a given value?](http://stackoverflow.com/questions/6171663/how-to-find-index-of-int-array-in-java-from-a-given-value) – Kindle Q Mar 29 '17 at 06:28
  • Your array `numbers[]` is declared but not populated. – naXa stands with Ukraine Mar 29 '17 at 07:02
  • Welcome to StackOverflow! Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – naXa stands with Ukraine Mar 29 '17 at 07:04

1 Answers1

1

your problem that you put if(numbers[x] % 2 == 0) outside for loop so you can't iterate over array by index x:

for (int x = 0; x < numbers.length; x++){
    if(numbers[x] % 2 == 0){
      System.out.print(numbers[x]);
    }
}
Oghli
  • 2,200
  • 1
  • 15
  • 37