How to print specific elements of an array?

Hi, I'm trying to print out parts of an array

If I have int[] numbers = {7, 3, 9, 1, 2, 8, 4, 5, 6, 10};

How can I print numbers above 5 from that array? I know I can just write print(numbers[0]), but that's not what I want... I tried a simple if and println; but that doesn't work ("The operator > is undefined for the argument type(s) int[], int).

I also tried to sort it (numbers = sort(numbers)) and then print all the elements from index 5 through 9, but I have no clue how to write one line to print multiple numbers. I searched a lot and I'm getting frustrated because it looks like it's extremely easy to do :(

Tagged:

Answers

  • _vk_vk
    Answer ✓

    The operator > is undefined for the argument type(s) int[], int

    you probably are doing numbers > 5 you can't compare an array with an int, as the message say, but you can compare each int hold by array int[]

    int[] numbers = {7, 3, 9, 1, 2, 8, 4, 5, 6, 10};
    for(int i=0; i < numbers.length; i++){
      int n = numbers[i];
      if(n > 5){
        println(n);
      }
    }
    
  • edited September 2015 Answer ✓

    Shorter version w/ "enhanced foreach" loop: :ar!

    byte[] numbers = { 7, 3, 9, 1, 2, 8, 4, 5, 6, 10 };
    for (byte n : numbers)  if (n > 5)  print(n, '\t');
    exit();
    
  • edited September 2015

    Thank you, both of you. I actually had something very close to what _vk wrote but got confused x) Argh!

Sign In or Register to comment.