Java数组中的最小值和最大值

19

我的代码没有错误,但是它没有显示最小值和最大值。代码如下:

Scanner input = new Scanner(System.in);

int array[] = new int[10];

System.out.println("Enter the numbers now.");

for (int i = 0; i < array.length; i++) {
    int next = input.nextInt();
    // sentineil that will stop loop when 999 is entered
    if (next == 999) {
        break;
    }
    array[i] = next;
    // get biggest number
    getMaxValue(array);
    // get smallest number
    getMinValue(array);
}

System.out.println("These are the numbers you have entered.");
printArray(array);


// getting the maximum value
public static int getMaxValue(int[] array) {
    int maxValue = array[0];
    for (int i = 1; i < array.length; i++) {
        if (array[i] > maxValue) {
            maxValue = array[i];
        }
    }
    return maxValue;
}

// getting the miniumum value
public static int getMinValue(int[] array) {
    int minValue = array[0];
    for (int i = 1; i < array.length; i++) {
        if (array[i] < minValue) {
            minValue = array[i];
        }
    }
    return minValue;
}

//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has  //been stored in an array!!!!!!!
public static void printArray(int arr[]) {
    int n = arr.length;

    for (int i = 0; i < n; i++) {
        System.out.print(arr[i] + " ");
    }
}

我需要使用 System.out.println() 才能显示它吗,还是直接返回就可以?


当然你需要打印这些数字。最好在调用它的地方打印。并且在 for 循环之外调用这两个方法。 - Rohit Jain
13个回答

18
getMaxValue(array);
// get smallest number
getMinValue(array);

您正在调用方法,但没有使用返回的值。

System.out.println(getMaxValue(array));
System.out.println(getMinValue(array)); 

17

如果您不想使用自己的方法,也可以尝试这种方法。

    Arrays.sort(arr);
    System.out.println("Min value "+arr[0]);
    System.out.println("Max value "+arr[arr.length-1]);

26
排序的时间复杂度为O(n*log(n)),查找最小/最大值的时间复杂度为O(n)。 - Tianxiang Xiong
提取答案...非常容易。 - Integraty_beast

6

以下是用于查找数组中最小值和最大值的工作代码。希望对您有所帮助:

 import java.util.Random;
 import java.util.Scanner;
 public class FindMin {
    public static void main(String[] args){
        System.out.println("Main Method Started");
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the size of the arr");
        int size = in.nextInt();
        System.out.println("Enter the maximum value of the arr");
        int max = in.nextInt();
        int [] arr  = initializeArr(max, size);
        print(arr);
        findMinMax(arr);
        System.out.println("Main Method Ended");
    }
    public static void print(int[] arr){
        for(int val:arr){
            System.out.print(val + " ");
        }
        System.out.println();
    }
    public static int[] initializeArr(int max,int size){
        Random random = new Random();
        int [] arr = new int[size];
        for(int ii=0;ii<arr.length;ii++){
            arr[ii]=random.nextInt(max);
        }
        return arr;
    }
    public static void findMinMax(int[] arr){
        int min=arr[0];
        int max=arr[0];
        for(int ii=0;ii<arr.length;ii++){
            if(arr[ii]<min){
                min=arr[ii];
            }
            else if(arr[ii]>max){
                max=arr[ii];
            }
        }
        System.out.println("The minimum in the arr::"+min);
        System.out.println("The maximum in the arr::"+max);
    }
}

可以用一行代码来完成冗长的方法。请查找最终解决方案。 - Arpan Saini

6

在我看来,其中最简单的解决方案之一是: -

//MIN NUMBER
Collections.sort(listOfNumbers);
listOfNumbers.get(0);

//MAX NUMBER
Collections.sort(listOfNumbers);
Collections.reverse(listOfNumbers);
listOfNumbers.get(0);

“Collections.reverse()” 是不必要的,因为排序列表中的最后一个值是最大值。 - Arun Joseph

5

在一行中求出数组的总和、最大值和最小值

 public static void getMinMaxByArraysMethods(int[] givenArray){

       //Sum of Array in One Line 
       long sumofArray =  Arrays.stream(givenArray).sum();

       //get Minimum Value in an array in One Line
        int minimumValue = Arrays.stream(givenArray).min().getAsInt();

        //Get Maximum Value of an Array in One Line
        int MaxmumValue =  Arrays.stream(givenArray).max().getAsInt();

    }

3
您只需要放弃Min/Max值即可:
  // get biggest number
  getMaxValue(array); // <- getMaxValue returns value, which is ignored
  // get smallest number
  getMinValue(array); // <- getMinValue returns value, which is ignored as well

你可以这样做:

  ... 
  array[i] = next;

  System.out.print("Max value = ");
  System.out.println(getMaxValue(array)); // <- Print out getMaxValue value

  System.out.print("Min value = ");
  System.out.println(getMinValue(array)); // <- Print out getMinValue value

  ...  

3
您在这里犯了两个错误。
1.在数组初始化完成之前调用了 getMaxValue(),getMinValue() 方法。
2.没有存储 getMaxValue(),getMinValue() 方法返回的返回值。
因此,请尝试使用以下代码。
   for (int i = 0 ; i < array.length; i++ ) 
  {
       int next = input.nextInt();
       // sentineil that will stop loop when 999 is entered
       if (next == 999)
       break;
       array[i] = next;
  }
  // get biggest number
  int maxValue = getMaxValue(array);
  System.out.println(maxValue );

  // get smallest number
  int minValue = getMinValue(array);
  System.out.println(minValue);

1
import java.util.*;
class Maxmin
{
    public static void main(String args[])
    {
        int[] arr = new int[10];
        Scanner in = new Scanner(System.in);
        int i, min=0, max=0;
        for(i=0; i<=arr.length; i++)
        {
            System.out.print("Enter any number: ");
            arr[i] = in.nextInt();          
        }
        min = arr[0];
        for(i=0; i<=9; i++)
        {
            if(arr[i] > max)
            {
                max = arr[i];
            }
            if(arr[i] < min)
            {
                min = arr[i];
            }
        }
        System.out.println("Maximum is: " + max);
        System.out.println("Minimum is: " + min);
    }
}

1
它无法正常工作,因为出现了以下错误: 主线程中的异常:java.lang.ArrayIndexOutOfBoundsException - user8001109

1

你的最大值和最小值方法是正确的

但你没有将整数打印到控制台!

也许更好的位置变更(最大值,最小值)方法

现在(最大值,最小值)方法在循环中。这是不必要的..只需要一次调用

我建议改变这段代码

    for (int i = 0 ; i < array.length; i++ ) {
       int next = input.nextInt();
       // sentineil that will stop loop when 999 is entered
       if (next == 999)
       break;
       array[i] = next;
}
System.out.println("max Value : " + getMaxValue(array));
System.out.println("min Value : " + getMinValue(array));
System.out.println("These are the numbers you have entered.");
printArray(array);

1

是的,你需要使用 System.out.println。但是每次输入一个值时,你都会得到最小值和最大值,并且如果他们提前退出,你不会跟踪元素的数量。

尝试:

for (int i = 0 ; i < array.length; i++ ) {
       int next = input.nextInt();
       // sentineil that will stop loop when 999 is entered
       if (next == 999)
           break;

       array[i] = next;
 }
 int length = i;
 // get biggest number
 int large = getMaxValue(array, length);
 // get smallest number
 int small = getMinValue(array, length);

 // actually print
 System.out.println( "Max: " + large + " Min: " + small );

然后你需要将长度传递给方法来确定最小值和最大值并进行打印。如果不这样做,其余字段将为0,可能会混淆正确的最小值和最大值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接