Java程序:在数组中查找最小和最大数量的3个数字

时间:2015-06-01 18:24:34

标签: java arrays loops

以下代码适用于最大值,但对于显示的最小值:对于我输入的任何3个值,最小数字为0 。非常感谢任何帮助。

import java.util.Scanner;

class MyClass{


        public static void main(String[] args) {
            // declare and create array object
            // declare smallest and largest int variables 
            int[] numbers;
            numbers = new int[3];
            int smallest = numbers[0], largest = numbers[0];

            // create Scanner object
            Scanner input = new Scanner(System.in);

            // prompt user 
            System.out.print("Please enter 3 numbers: \n");
            // use for loop to obtain user input
            for (int counter = 0; counter < numbers.length; counter++) {
                numbers[counter] = input.nextInt();
            } // end obtaining input

            // for loop to find largest and smallest values
            for (int i=0 ;i< numbers.length; i++) {
                if (numbers[i] < smallest) {
                    smallest = numbers[i];
                } // end finding smallest
                if (numbers[i] > largest) {
                    largest = numbers[i];
                } // end finding largest number       

            }

            System.out.println("largest number is "+largest);
            System.out.println("smallest number is "+smallest);

        }   

}

3 个答案:

答案 0 :(得分:2)

最小值始终在此处初始化为0:int smallest = numbers[0]。除非用户输入小于0的值,否则最小值将保持为0.使用Integer.MAX_VALUEint smallest = Integer.MAX_VALUE)代替确保实际选择的最小数字。

答案 1 :(得分:0)

您正在将smallest初始化为0,因此,如果数组中的数字都不到0,那么您仍会获得0 } 作为结果。而是将其初始化为Integer.MAX_VALUE,这是整数数据类型可以具有的最高值。

答案 2 :(得分:0)

import java.util.Scanner;

class MyClass {
    public static void main(String[] args) {
        // declare and create array object
        // declare smallest and largest int variables 
        int[] numbers;
        numbers = new int[3];

        // create Scanner object
        Scanner input = new Scanner(System.in);

        // prompt user 
        System.out.print("Please enter 3 numbers: \n");
        // use for loop to obtain user input
        for (int counter = 0; counter < numbers.length; counter++) {
            numbers[counter] = input.nextInt();
        } // end obtaining input

        //Use in built Math.min and Math.max to get smallest and largest numbers
        System.out.printf("%s: %d%n", "smallest number is ", Math.min(numbers[0], Math.min(numbers[1], numbers[2])));
        System.out.printf("%s: %d%n", "largest number is ", Math.max(numbers[0], Math.max(numbers[1], numbers[2])));
    }
}