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