簡體   English   中英

如何使此代碼屈光並獲得陣列中所有學生的總體平均分

[英]How to refractor this code and get the average of all students overall mark in the array

客戶類別

public class Assignment2Q1 {
    public static void main(String[] args) 
    {
        int sum;
        String choice;
        String option;
        Scanner reader = new Scanner(System.in);

            System.out.println("What is your option");
            option = reader.next();
            Student   [] Studentlist ;
            int numofStudent = 0;
            while("Add".equalsIgnoreCase(option))
            {      
               System.out.println("How many student would you like to enter: ");
                        numofStudent=reader.nextInt();
                        Studentlist=new Student [numofStudent];

                        for(int i=0;i<numofStudent;i++)
                        {
                            Studentlist[i] =new Student();
                            Studentlist[i].inputDetails();

                        }
                        System.out.println("What is your option");
                        choice = reader.next();
                        while("TotalAVG".equalsIgnoreCase(choice))
                        {
                            for(int i=0;i<Studentlist.length;i++)
                            {
                                Studentlist[i].avg();
                            }
                            System.out.println("What is your option");
                            choice = reader.next();
                        }


                        System.out.println("What is your option");
                        choice = reader.next();

            }

   //Input Method
    public void inputDetails()
       {
        System.out.println("Please Enter The Score of Assignemt 1:");
        ass01=reader.nextInt();
        System.out.println("Please Enter The Score of Assignemt 2:");
        ass02=reader.nextInt();
        System.out.println("Please Enter The Total Mark of Weekly Pratice Work:");
        weeklyWork=reader.nextInt();
        System.out.println("Please Enter The Score of Final Exam:");
        finalExam=reader.nextInt();
       }

    //Average method
    void avg()
       {
       int count = 0;
       int overallMark =0;
       int sum = 0;
        overallMark = (ass01/5)+(ass02/5)+weeklyWork+(finalExam/2);
        sum = sum+overallMark;
        count = count +1;
        System.out.println("The average: "+(sum/count) );
       }

我有問題是當我嘗試輸入TotalAVG時,它顯示了兩個輸出

平均:50

平均:3

總體標記位於子類中,

  1. 我如何收集所有總體得分並進行平均

  2. 如何修改此代碼?

在您的avg()方法中:

  1. 您聲明int sum = 0; 然后向其添加另一個變量: sum = sum+overallMark; 因此sum將始終包含overallMark
  2. 另一個類似的問題是count :您在avg()聲明: int count = 0; 然后加1: count = count +1; 因此它將始終具有值1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM