如何在不使用函数的情况下在java中查找数组中的最大/最小值

时间:2016-12-24 11:21:32

标签: java

import java.util.Scanner;

/**
 *
 * @author JEEWAT RAM
 */
public class Task5lab8 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        Scanner in = new Scanner(System.in);
        System.out.println("enter range of numbers you want in array:");

        int a = in.nextInt();
        int[] numbers = new int[a];
        System.out.println("enter all numbers: ");
        for (int i = 0; i < a; i++) {

            numbers[i] = in.nextInt();

        }
    }
}

2 个答案:

答案 0 :(得分:0)

只需你可以使用这样的条件:

//first we will consider that our min value is the first on in the array
int min = numbers[0];
//check every element with this min
for (Integer n : numbers) {
    //if this value in less then the first value change the min with this value
    if (min > n) {
        min = n;
    }
}

与max相同:

int max = numbers[0];
for (Integer n : numbers) {
    if (max < n) {
        max = n;
    }
}

答案 1 :(得分:0)

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

for (int n : numbers) {
    if (n > max) {
        max = n;
    }
    if (n < min) {
        min = n;
    }
}