0

I am making a program that finds the min/max numbers in a java array. I am currently stuck at the last part which is finding the min/max. I have currently setup all other parts of the program. This is my code.

import java.util.Scanner;
public class X {
public static void main (String[] args) {
    Scanner input= new Scanner(System.in);
    System.out.println("Enter size of array");
    int n= input.nextInt();
    int[] x= new int[n];
    System.out.println("Enter Array nums");
    for(int i=0;i<n;i++){
        x[i]= input.nextInt();
    }}}
A. Smith
  • 1
  • 2

4 Answers4

1
Arrays.sort(x);

sorts the array, so after doing that all you need to do is look in the first and last element to find the min and max.

nhouser9
  • 6,730
  • 3
  • 21
  • 42
0

You can use the following methods to directly find the max and min.

List list = Arrays.asList(x);
System.out.println(Collections.min(list));
System.out.println(Collections.max(list));
Imesha Sudasingha
  • 3,462
  • 1
  • 23
  • 34
0

simple.

So Simple actually

public static void main(String[] args)
{
    Scanner input= new Scanner(System.in);
System.out.println("Enter size of array");
    int n= input.nextInt();
    int[] x= new int[n];
    System.out.println("Enter Array nums");
    for(int i=0;i<n;i++){
        x[i]= input.nextInt();
    }}}
    Arrays.sort(x);
    System.out.println(String.format("Min= %d Max= %d",x[0],x[x.length -1]));
}
Theresa Forster
  • 1,914
  • 3
  • 19
  • 35
0
import java.util.Scanner;
public class X {
public static void main (String[] args) {
Scanner input= new Scanner(System.in);
System.out.println("Enter size of array");
int n= input.nextInt();
int[] x= new int[n];
int min_num,max_num;
System.out.println("Enter Array nums");
for(int i=0;i<n;i++){
    x[i]= input.nextInt();
    if(i==0){
        min_num=max_num=x[i];
    }else{
        if(x[i]>max_num)
        max_num=x[i]; 
        if(x[i]<min_num)
        min_num=x[i];
    }}}