使用索引的最小和最大数字数组?

时间:2017-04-20 15:27:15

标签: java arrays

我正在创建一个程序,要求用户输入十个数字,然后输出最小和最大的数字。这是我的代码:

import java.util.Scanner; // program uses Scanner
public class ArrayTester {
// begin execution
public static void main(String[] args) {
    // declare and create array object
    // declare smallest and largest int variables 
    int[] numbers;
    numbers = new int[10];
    int smallest = numbers[0], largest = numbers[0];

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

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

    // enhanced for loop to find largest and smallest values
    for (int i : numbers) {
        if (i  < smallest) {
            smallest = i; 
        } // end finding smallest
        else if (i  > largest) {
            largest = i; 
        } // end finding largest number 
    } // end finding largest and smallest values

    // for loop to print user input 
    System.out.printf("%s%8s\n", "Index", "Input");
    for (int counter = 0; counter < numbers.length; counter++) {
        System.out.printf("%5d%8d\n", counter, numbers[counter]);
    } // end printing input values

    // print smallest and largest numbers
    System.out.printf("Smallest number: %d\nLargest number: %d\n", smallest, largest);

} // end main
} // end ArrayTester

我遇到的问题是当数字输出时,它给出0作为最小值,9作为最大值。我知道这是因为10数组但是如何修复以显示最小整数和最大整数?

2 个答案:

答案 0 :(得分:0)

numbers = new int[10];

上面的语句使用全0来初始化数组,因为您要将numbers[0]分配给smallest,它始终为0

此外,实现此目的的另一种方法是使用Java 8 stream,例如:

int[] array = new int[] {1,2,3,10,0};
IntSummaryStatistics summaryStatistics = Arrays.stream(array).summaryStatistics();
System.out.println(summaryStatistics.getMax());
System.out.println(summaryStatistics.getMin());

答案 1 :(得分:0)

把这一行:

int smallest = numbers[0], largest = numbers[0];

在这一行之下:

for (int counter = 0; counter < numbers.length; counter++) {
    numbers[counter] = input.nextInt();
} // end obtaining input

您正在初始化&#34;最小的&#34;为0,因为你的数组还没有任何值。除非用户输入负数,否则最小值将始终为零。