Home > Software engineering >  print max num in an array in java
print max num in an array in java

Time:02-17

import java.util.Scanner;

public class maxnuminarray {
    public static void main(String[] args) {
        int temp;
        System.out.print("please insert the size for array:");
        Scanner input = new Scanner(System.in);
        int size = input.nextInt();
        int[] nums = new int[size];

        for (int i = 0; i < size; i  ) {
            System.out.print("please insert your desired nums:");
            nums[i] = input.nextInt();
        }

        for (int i = 1; i < size; i  )
            for (int j = 0; j < size - i; j  )
                if (nums[i] > nums[i   1]) {
                    temp = nums[i];
                    nums[i] = nums[i   1];
                    nums[i   1] = temp;
                }

        System.out.print(nums[size - 1]);
    }
}

Though it gets all the values for the array, it still doesn't print the max number which is the last num in the array.

The error I get for size=5:

Exception in thread "main": java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 at maxnuminarray.main(maxnuminarray.java:15)

CodePudding user response:

import java.util.Scanner;
public class maxnuminarray {
public static void main(String[] args) {
    int temp;
    System.out.print("please insert the size for array:");
    Scanner input = new Scanner(System.in);
    int size = input.nextInt();
    int[] nums = new int[size];
    for (int i = 0; i < size; i  ) {
        System.out.print("please insert your desired nums:");
        nums[i] = input.nextInt();
    }
    int max = nums[0];
    for (int i = 1; i < size; i  )
       if(max < nums[i])
          max = nums[i];
   }
   System.out.println("Max "   max);
}

CodePudding user response:

Once you read in the values, iterate over the array like this.

int max = Integer.MIN_VALUE;
for (int n : nums) {
   max = Math.max(max, n);
}
  • Related