gpt4 book ai didi

java - 使用非空方法打印一系列问题的摘要

转载 作者:行者123 更新时间:2023-12-02 02:09:03 24 4
gpt4 key购买 nike

嘿。我写了这段代码

import java.util.Scanner;
public class SportsEvents {
public static void main(String[] args) {
String[] contestants = getcontestants();
int[] score=getscores();
System.out.println("The maximum score is: "+getMaxValue(score));
System.out.println("The minimum score is: "+getMinValue(score));
System.out.println("The average is: "+getAverage(score));
}
public static String[] getcontestants()
{
int numcontestants=1;
String name[] = new String[numcontestants];

for(int j=0;j<numcontestants;j++){
Scanner ip=new Scanner(System.in);
System.out.println("Enter contestant's name");
name[j]=ip.nextLine();
}
return name;
}
public static int[] getscores()
{
int numscores=8;
int score[] = new int[numscores];
for (int a=0;a<numscores;a++){
Scanner ip=new Scanner(System.in);
System.out.println("Enter the scores");
score[a]=ip.nextInt();
}
return score;
}
public static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxValue = array[i];
}
}
return maxValue;
}
public static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
public static int getAverage(int[] people) {
int sum = 0;
for (int i=0; i < people.length; i++) {
sum = sum + people[i];
}
int result = sum / people.length;
return result;
}
}

正如您所看到的,用户输入一个名字和 8 个分数,计算机会找到最大分数、最低分数和平均值。我想要一个非空方法来总结所有内容,但我不知道该怎么做。例如:如果我输入 James 作为名字和数字 1-8,我希望它打印: 参赛者是 James,他的最高分是 8。他的最低分是 1。他的平均分是 49。谢谢您,如果感到困惑请告诉我!!

最佳答案

您想要的是将即时结果存储到包含 min、max、avg 的单个对象中。

在 java 8 中已经有一个开箱即用的方法供您使用:

int[] score=getscores();
IntSummaryStatistics stats = Arrays.stream(score).summaryStatistics();

IntSummaryStatistics 包含

private long count;
private long sum;
private int min;
private int max;

您也可以手动获取结果:

首先定义一个类来保存您的数据:

public class SportsEvents {

public static class IntArrayStatistic {
private int min = Integer.MAX_VALUE;
private int max = Integer.MIN_VALUE;
private int sum = 0;
private int avg;
private int count;

// Getter - Setter

public static IntArrayStatistic of(int[] input) {
if (input == null) {
throw new IllegalArgumentException("Null array");
}
IntArrayStatistic result = new IntArrayStatistic();
result.count = input.length;

for (int i : input) {
if (i < result.min) {
result.min = i;
}
if (i > result.max) {
result.max = i;
}
result.sum += i;
}
result.avg = result.sum / result.count;
return result;
}
}
}

并使用这个:

int[] score=getscores();
IntArrayStatistic stats = IntArrayStatistic.of(score);

关于java - 使用非空方法打印一系列问题的摘要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50303035/

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