I am trying to find the max integer of an array where number = [10]. My method prints out 0, not the max integer.
public static void maxArr (int[] number){
int max = number[0];
for(int i = 1; i<number.length; i++){
if(number[i]> max){
max = number[i];
}
} System.out.print(max);
}
You aren’t filling your array correctly.
In java, when you first create an array with
private int[] myArray, it is null (that is, it doesn’t represent an actual thing yet, it’s just a name that could point to an array in the future). Next, you somehow tell it how many elements it will hold. There are 2 commonly used ways to do this:The first is something that looks like
myArray = new int[42];This will initialize the array, but every slot will be zero (or worse, null if it’s an array of Objects). You can fill one of its individual slots (in this case, the 4th slot) withmyArray[3] = 13. This will store the int 13 in slot 3 of myArray. Array slots start counting at 0, so if you want the first element you callmyArray[0], if you want the second one you callmyArray[1], and so on. You can use a for loop to populate an entire array with just a few lines of code:Your array is now ready to be used for whatever its purpose in life happens to be.
The second way to fill your array happens when you initialize it. It looks like
myArray = new int[] {10, 42, 24, 64, 8, 16, 3};Anything you put into the curly brackets is now in the array, so the value ofmyArray[0]is now 10, and the value ofmyArray[1]is now 42, and so on.