gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:44:06 24 4
gpt4 key购买 nike

我应该制作一个程序,从用户输入中获取 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

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

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)

我需要一个 try and catch block 来解决这个问题吗?

最佳答案

您的问题与您在其他答案中已经说明的 for 循环的使用方式有关。不过,Java 8 中更短的方法是使用流:

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

关于Java - 使用数组查找最大和最小数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29736100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com