繁体   English   中英

Java Scanner 输入到 int 和 string 数组

[英]Java Scanner input into int and string arrays

如果有人愿意帮助我使用这个程序,我将不胜感激,它使用扫描仪接受多个学生的姓名和成绩,然后将它们放入 2 个数组中,学生和分数。 然后它会打印出如下所示...

最大限度。 等级 = 98 (劳伦)

最小。 等级 = 50(乔)

平均等级 = 83.9

/* Chris Brocato
 *  10-27-15
 * This program will read the students names and scores using a Scanner and use two arrays to 
 * show the grade and name of the highest and lowest scoring student as well as the average grade.*/

import java.util.*;

public class StudentCenter {

    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        System.out.print("Please enter the number of students: ");
        int students = console.nextInt();
        String[] name = new String[students];
        int[] scores = new int[students];

        int min = 0; int max = 0; int sum = 0;
        for (int i = 0; i < name.length; i++) {
            System.out.print("Please enter student's name: ");
            name[i] = console.next();
            System.out.print("Now enter their score: ");
            scores[i] = console.nextInt();
            if (i == 0) {
                min = students;
                max = students;
            }else {
                if (students < min) min = students;
                if (students > max) max = students;
            }sum += students;
        }
        System.out.println("Min. Grade = " + min + name );
        System.out.println("Max. Grade = " + max + name);
        System.out.println("Average Grade = " + sum);
        double avg = (double) sum / (double) students;
        System.out.println("Avg = " + avg);
        console.close();
        }   

    }

您将minmaxsum设置为min的值,即students的数量,而不是他们的分数。 您可能应该将它们设置为scores[i]

if (i == 0) {
    min = scores[i];
    max = scores[i];
}else {
    if (students < min) min = scores[i];
    if (students > max) max = scores[i];
}
sum += scores[i];

我还将存储最小和最大分数的索引,以便您以后可以参考它们的名称。

 min = scores[i];
 minIndex = i;
 ...
 System.out.println("Min. Grade = " + min + name[minIndex] );

我将使用 Min 和 Max 值作为常量。

int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int maxValue = 0;
int minValue = 0;
String minName;
String maxName;

//then use them for comparison in the loop

if(scores[i] < min)
{
 minValue = scores[i];
 minName = name[i];
}

if(scores[i] > max)
{
 maxValue = scores[i];
 maxName = name[i];
}

这将使用关联的名称存储您的最大值/最小值。

您正在将 min 和 max 与不正确的值进行比较。 学生是你没有成绩的学生人数。 此外,在打印名称时,您正在打印整个数组,而不仅仅是特定值。 所以我的建议是你创建两个这样的变量:

int minInd = 0; int maxInd = 0;

然后像这样改变你的 if:

if (i == 0) { min = scores[i]; max = scores[i]; } else { if (scores[i] < min) { min = scores[i]; minInd = i; } if (scores[i] > max) { max = scores[i]; maxInd = i; } } sum += scores[i];

并像这样打印结果:

System.out.println("Min. Grade = " + min + " ("+ name[minInd]+")"); System.out.println("Max. Grade = " + max + " ("+name[maxInd]+")");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM