Java - 使用数组查找最大和最小数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29736100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:49:15  来源:igfitidea点击:

Java - Finding Largest and Smallest Numbers using an Array

javaarrays

提问by Christian Lapinig

I am supposed to make a program that takes 10 numbers from a user input, find the largest and smallest number and display all the inputs from the user. This program does use an array. Here is my code:

我应该制作一个程序,从用户输入中获取 10 个数字,找到最大和最小的数字并显示用户的所有输入。这个程序确实使用了一个数组。这是我的代码:

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 (numbers[i] < smallest) {
                smallest = numbers[i];
            } // end finding smallest
            else if (numbers[i] > largest) {
                largest = numbers[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);
        System.out.print("Programmed by Christian Lapinig");
    } // end main
 } // end ArrayTester

At this point I am able to obtain user inputs, but I run into this problem:

此时我能够获得用户输入,但我遇到了这个问题:

Please enter 10 numbers: 
454
392
33
41
6
44
39
21
12
2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 454
at ArrayTester.main(ArrayTester.java:32)

Would I need a try and catch block to fix this?

我需要一个 try 和 catch 块来解决这个问题吗?

采纳答案by Danny

A try-catchwould just swallow the exception. Your problem is that the enhanced for loop is iterating over the valuesof the array, but you're treating it like it's the index, so you check numbers[454]and immediately blow up because you're outside the length of the array.

Atry-catch只会吞下异常。您的问题是增强的 for 循环正在迭代数组的,但您将其视为索引,因此您检查numbers[454]并立即爆炸,因为您超出了数组的长度。

Either iterate over the indexes, or just work with the values directly:

要么迭代索引,要么直接处理值:

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

回答by Bubletan

Your problem is related to the way you use the for-loop as already stated in the other answers. A shorter approach in Java 8 though, would be using a stream:

您的问题与您使用 for 循环的方式有关,如其他答案中所述。不过,Java 8 中更短的方法是使用流:

IntStream.of(numbers).max()and IntStream.of(numbers).min()

IntStream.of(numbers).max()IntStream.of(numbers).min()

回答by mtyurt

for (int counter = 0; counter <= numbers.length; counter++) 

You put =<, instead you should put <. if counter equals to length, it tries to reach out of range because indexes start from zero.

你放=<,而不是你应该放<。如果计数器等于长度,它会尝试超出范围,因为索引从零开始。

回答by almeynman

CHange

改变

for (int i : numbers) {

to

for (int i=0;i<numbers.length;i++) {

回答by AlexR

Your problem is in this loop:

你的问题在这个循环中:

for (int i : numbers) {

This loop means iterates over the elements of the array, not its indexes. So, you can say:

这个循环意味着迭代数组的元素,而不是它的索引。所以,你可以说:

for (int a : numbers) {
   if(a > ...) {
   ....
}

Alternatively you can use array index like the following"

或者,您可以使用如下所示的数组索引”

for (int i = 0; i < numbers.lenth; i++) {
   if(numbers[i] > ...) {
   .....
}

回答by Prasaanth Neelakandan

Change it to :

将其更改为:

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

AND <= to <

AND <= 到 <

for (int counter = 0; counter < numbers.length; counter++) {
            System.out.printf("%5d%8d\n", counter, numbers[counter]);
        } 

Try catch block will simply handle your error in a graceful way . It won't solve your problem.

Try catch 块将简单地以优雅的方式处理您的错误。它不会解决你的问题。

回答by Brett Okken

In java 8, you can obtain an IntStreamand get the summary statistics.

在 java 8 中,您可以获取IntStream并获取汇总统计信息

final IntSummaryStatistics stats = IntStream.of(numbers).summaryStatistics();

回答by Volk64

As many people pointed out, you are using the values of your for-each loop as and index, meaning your code tries to access the position of whatever number your user inputs in your array.

正如许多人指出的那样,您正在使用 for-each 循环的值作为和索引,这意味着您的代码尝试访问用户在数组中输入的任何数字的位置。

So to fix it, you just need to do

所以要修复它,你只需要做

smallest = i;

and

largest = i;

回答by Shiva

Try code below,

试试下面的代码,

import java.util.Scanner;

public class LargestSmallest
{
   public static void main(String[] args)
   {
      // assigning array of 10 numbers to numerals

      int a;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter number of elements to find largest and smallest number: ");
      a = sc.nextInt();
      int numerals[] = new int[a];
      System.out.println("Enter " + a + " integers.");

      for(int b = 0;b < a;b++)
         numerals[b] = sc.nextInt();

      // assigning first numeral of an array to largest and smallest

      int largest = numerals[0];
      int smallest = numerals[0];

      for(int x = 1;x < numerals.length;x++)
      {
         if(numerals[x] > largest)
            largest = numerals[x];
         else if(numerals[x] < smallest)
            smallest = numerals[x];
      }
      System.out.println("Largest Number is: " + largest);
      System.out.println("Smallest Number is: " + smallest);
   }
}

For more on finding largest and smallest numbers using an array click here.

有关使用数组查找最大和最小数字的更多信息,请单击此处