简体   繁体   中英

Find the minimum and maximum number in an Array in Java

I'm new to programming. I want to find the maximum and minimum number in a given array. So I wrote this code. Although this gives the correct minimum number, it gives multiple maximum numbers. Can someone help me with this?

package maximumandminimum;

public class Maximumandminimum {

public static void main(String[] args) 
{
  int arr[] = {33,55,80,90,12,56,78};

          int min = arr[0];
          int max = arr[0];

          for(int i = 0; i< arr.length;i++)
          {
              if(arr[i]<min){
                  min= arr[i];
                  System.out.println("minumum number is"+min);
              }
              if(arr[i]>max){
               max = arr[i];
               System.out.println("maximum number is"+max);

          }

          }
}

}

This has been solved here: Finding the max/min value in an array of primitives using Java

Don't forget to print outside the loop (to get one answer).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM