簡體   English   中英

如何在不使用函數的情況下在Java中的數組中找到最大值/最小值

[英]how to find max/min value in array in java without using functions

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();

        }
    }
}

只需使用以下條件即可:

//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;
    }
}
int max = numbers[0];
int min = max;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM