Larger Than N Array

I've been having trouble trying to write a method that accepts two arguments: an array and a number n with all of them assumed to be integers. It should also display the numbers in the array that are greater than the number n.

This is my first time ever working with arrays, and trying to do this sort of thing. So, I am very unsure about what to do, or how to do it with this question.

import java.util.Random; // Initialize random class
import java.util.Scanner; //Create the scanner class

public class ArrayNumbers {

    public static void getNumbers(int computerArray[], int n){

        for(int element : computerArray){
            if(n < element){
            System.out.println(element);
            }
        }
    }

    public static void main(String[] args) {
        int computerArray1[] = new int[100];
        Random rand = new Random();

        for(int count1=10; count1>1; count1++){
            computerArray1[n] = rand.nextInt(100);
            getNumbers(computerArray1[1],1);
       }
    }
}
1

2 Answers

change your main to be (see comments inline)

public static void main(String[] args) {
    int computerArray1[] = new int[100];
    Random rand = new Random();

    for(int count1=0; count1 < 100; count1++){  // loop to 100
        computerArray1[count1] = rand.nextInt(100);  // n does not exist
   }
   // do after data is input?
   getNumbers(computerArray1,1);  // pass the whole array

}   
    int computerArray1[] = new int[100];

Based on the size of your array here which is 100 the app will crash when count1 reaches 100 because the array is only addressable from 0-99.

    for(int count1=10; count1>1; count1++){
        computerArray1[n] = rand.nextInt(100); // count1 instead of n?      
        // computerArray1[1] is just the int at index 1 in the array
        getNumbers(computerArray1[1],1); 
   }

So what you might be intending to do is this...

    for(int count1=0; count1<100; count1++){
        computerArray1[count1] = rand.nextInt(100);
        getNumbers(computerArray1,1);
   }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest