gpt4 book ai didi

java - 从数组中获取最小值和最大值 - Java

转载 作者:行者123 更新时间:2023-12-01 13:57:29 24 4
gpt4 key购买 nike

import java.util.Scanner;

public class Sales {
public static void main(String[] args) {
int[] sales;
sales = getSales();
printSales(sales);
printSummary(sales);
}

private static int[] getSales() {
Scanner input = new Scanner(System.in);
int[] temp;
System.out.print("Enter the number of salespeople: ");
temp = new int[input.nextInt()];

for (int i = 0; i < temp.length; i++) {
System.out.print("Enter sales for salesperson " +
(i + 1) + ": ");
temp[i] = input.nextInt();
}
return temp;
}

private static void printSales(int[] s) {
System.out.println();
System.out.println("Salesperson Sales");
System.out.println("----------- -----");
for (int i = 0; i < s.length; i++) {
System.out.printf("%6d%12d\n", i + 1, s[i]);
}
}

private static void printSummary(int[] s) {
int sum = 0;
int max_sale = 0; // Salesperson with the most sales
int min_sale = 0; // Salesperson with the least sales

for (int i = 0; i < s.length; i++) {
sum = (s[i] + sum);
if (s[i] > max_sale)
max_sale = s[1];
else if (s[i] > min_sale)
s[i] = min_sale;
}
System.out.println();
System.out.println("Total sales: " + sum);
System.out.println("Average sales: " + (double)sum / s.length);
System.out.println("Salesperson " + (max_sale + 1) +
" had the maximum sale with " +
s[max_sale]);
System.out.println("Salesperson " + (min_sale + 1) +
" had the minimum sale with " +
s[min_sale]);
}
}

该应用程序的目的是将销售人员的数量及其销售额作为输入,然后显示个人销售额、总销售额和平均值。这工作正常,但它还应该显示哪个销售人员的最大和最小销售额以及它们的金额(第 51 - 54 行)。目前,只要最大值大于销售人员的数量,我就会收到 ArrayIndexOutOfBoundsException 异常,并且出于某种原因无法弄清楚。

最佳答案

1 - 修改 for 循环以获取最大值和最小值,而不修改数组
2 - 尝试打印 max 和 min 而不是打印 sum[max]some[min] (这可能会抛出 IndexOutOfBoundsException)3 - min_sale 应大于 0,实际上是一个足够大的值(因为数组中只能包含正值)

总结一下:

    int sum      = 0;
int max_sale = Integer.MIN_VALUE; // Salesperson with the most sales
int min_sale = Integer.MAX_VALUE; // Salesperson with the least sales

for (int i = 0; i < s.length; i++){
sum = (s[i] + sum);
if (s[i] > max_sale)
max_sale = s[i];
else if (s[i] < min_sale)
min_sale = s[i];
}

System.out.println("Salesperson " +
" had the maximum sale with " +
max_sale);
System.out.println("Salesperson " +
" had the minimum sale with " +
min_sale);

关于java - 从数组中获取最小值和最大值 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19551223/

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