【问题标题】:Java: coding that uses a variable to specify array length?Java:使用变量指定数组长度的编码?
【发布时间】:2012-05-28 02:18:43
【问题描述】:

我正在开发一个学生分数应用程序,该应用程序接受一个或多个学生的姓氏、名字和分数,并将结果存储在一个数组中。然后它按姓氏的字母顺序打印学生和他们的分数。我们不知道有多少学生,但会少于 100 人。

我们必须在学生信息的末尾显示班级平均分,并在每个成绩低于班级平均分 10 分以上的学生之后显示一条消息。

我的第一个问题是我创建了一个 do/while 循环来询问用户是否想输入另一个,但它不起作用!?!?

其次,我不知道如何在个别学生身上显示“低于 10 分”的消息。

public class Student implements Comparable
{
    String firstName;
    String lastName;
    int score; 

    //stores last name, first name and score for each student
    public Student(String lastName,String firstName,int score)
    {
        this.lastName = lastName;
        this.firstName = firstName;
        this.score = score;    
    }
    //implement the comparable interface so students can be sorted by name
    public int compareTo(Object o)
    {
        Student otherStudent = (Student)o;

        if(otherStudent.lastName.equals(lastName))
            {
            return firstName.compareToIgnoreCase(otherStudent.firstName);
            }
        else
            {
            return lastName.compareToIgnoreCase(otherStudent.lastName);
            }
    }
    public String toString()
    {
        return lastName + ", " + firstName + ": " + score; 
    }
}

import java.util.Scanner;
import java.util.Arrays;

public class StudentApp
{
    static Scanner sc = new Scanner(System.in);

    public static void main(String [] args)
    {
        Student [] studentArray;
        String lastName;
        String firstName;
        int score = 0;
        double average = 0;


        System.out.println("Welcome to the Student Scores Application.");
        System.out.println();

        do{

            //code that uses variable to specify the array length
        int nStudent = 100;  //array size not set unit run time
        studentArray = new Student[nStudent];

            for (int i=0; i<nStudent; i++)
            {
            System.out.println();

            lastName = Validator.getRequiredString(sc, 
                           "Student " + (i+1) +  " last name: ");
            firstName = Validator.getRequiredString(sc, 
                           "Student " +  " first name: ");               
            score = Validator.getInt(sc, 
                         "Student " + " score: ",
                        -1, 101);

            studentArray[i] = new Student(lastName, firstName, score);

            double sum = 0.0;
            sum += score;
            average = sum/nStudent;
            }
        }while (getAnotherStudent());

        Arrays.sort(studentArray);

        System.out.println();

        for (Student aStudent: studentArray)
        {
            System.out.println(aStudent);
            if (score<= (average-10))
            {
                System.out.println ("Score 10 points under average");
            }
        }
        System.out.println("Student Average:" +average);
    }
    public static boolean getAnotherStudent()
    {
        System.out.print("Another student? (y/n): " );
        String choice = sc.next();
        if (choice.equalsIgnoreCase("Y"))
            return true;
        else
            return false;
    }
}

【问题讨论】:

    标签: java arrays


    【解决方案1】:

    这里有几个问题:

    • 每次执行...同时,您都会重新实例化studentArraysum。这意味着当 getAnotherStudent() 为真时,您之前迭代的所有数据都将被核对 - 您希望实例化数组并只求和一次
    • 如果您有超过 100 名学生,您不会停止。您的循环中也需要一个围绕 nStudent 的结束条件。
    • 您应该对getAnotherStudent() 进行一些调整,以便您可以阻止数据,并在输入有效数据时等待 - 通过使用循环:

       public static boolean getAnotherStudent() {
           Scanner sc = new Scanner(System.in);
           System.out.print("Another student? (y/n): " );
           if (sc.hasNext()) {  
               String choice = sc.next();
               // blocks here - ignores all input that isn't "y" or "n"
               while(!((choice.equalsIgnoreCase("Y") || choice.equalsIgnoreCase("N")))) {
                   if (choice.equalsIgnoreCase("Y")) {
                       return true;
                   }
                   System.out.print("Another student? (y/n): " );
                   choice = sc.next();
               }
            }
            return false; // obligatory
      

    【讨论】:

    • 当用户输入“n”时,您的阻止代码位于循环中。如果您将 while 循环更改为 ||,它可以正常工作。并将你的 if 移到循环之外。
    • 我很惊讶我错过了。谢谢@Glitch。
    【解决方案2】:

    您的代码很接近,只是有几个问题。你的 do while 循环不起作用的原因是你里面有一个 for 循环。这意味着您将询问 100 名学生,然后再询问他们是否要添加另一名学生。您的总和正在此循环中创建,因此每次都会重置。

    最后,您不知道将添加多少学生,但您的代码假定将有 100 名学生。这意味着您不能使用 for each 循环遍历数组,因为有些可能为空。只需使用常规 for 循环直到您添加的学生的最后一个索引。以下是更改:

        Student[] student = new Student[nStudent]; 
        int studentCount = 0; //declear the counter outside the loop
        double sum = 0.0; //declear the sum outside the loop
        do {
            System.out.println();
            lastName = Validator.getRequiredString(sc, 
                           "Student " + (i+1) +  " last name: ");
            firstName = Validator.getRequiredString(sc, 
                           "Student " +  " first name: ");          
            score = Validator.getInt(sc, 
                         "Student " + " score: ",
                        -1, 101);
    
            student[studentCount] = new Student(lastName, firstName, score); 
    
            sum += score; //increase the sum
    
            studentCount++; //increment the counter
    
        } while (studentCount < nStudent && getAnotherStudent()); //stop if the user says 'n' or we hit the maximum ammount
        average = sum / studentCount; //work out the average outside the loop
    
        System.out.println();
    
        for (int i= 0; i< studentCount; i++ ) {
            System.out.println(aStudent);
            if (score <= (average - 10)) {
                System.out.println("Score 10 points under average");
            }
        }
        System.out.println("Student Average:" + average);
    }
    

    【讨论】:

    • 如果赋值需要一个数组,则不应有偏差。解决这个问题。
    • 由于更改,将 ArrayList 更改为数组,并将每个数组的结尾更改为正常的 for 循环。
    【解决方案3】:

    您的 getAnotherStudent() 方法应为:

    System.out.print("Another student? (y/n): " );
    if (sc.hasNext()) {   // blocks until user entered something     
        String choice = sc.next();
                if (choice.equalsIgnoreCase("Y"))
                    return true;
                else
                    return false;
    } else {
        // won't come here
        return false;
    }
    

    【讨论】:

    • 它一直等到用户输入一些东西,但是当我输入“m”而不是指定的“n”时中止是不好的设计。
    • @Makoto 如果您认为这是个好主意,您可以编辑答案以限制接受用户输入,而不是投票。但是,我更喜欢不会一直困扰我的应用程序,因为我没有准确地输入它所期望的内容,而不是在发生这种情况时使用一些默认值......
    • 我没有编辑你的答案。如果你觉得它的方式很好,那么你可以无视谁对你投了反对票。我只是对可用性和设计有强烈的感觉;如果我想通过输入“n”来取消,它应该只响应“n”而不是“6”。但同样,如果您对此感到满意,请不要担心。
    猜你喜欢
    • 2017-11-15
    • 2017-03-17
    • 1970-01-01
    • 2011-04-03
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多