Java GPA计算(如何设置无限数组?)

时间:2011-12-25 00:49:15

标签: java arrays swing

基本上,我的问题是我不确定如何从用户设置无限输入数组。 目前,只有当用户准确输入6个主题时,计算才会顺利进行,但如果输入的主题少于或大于6,则计算不正确。 不知何故,我想让输入无限制。

这是我到目前为止所做的:

主要课程

import javax.swing.*;

public class CGPAMain extends JFrame
{
  public static void main(String[] args)
  {
    JFrame frame = new JFrame("GPA Calculation");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    MainPage panel = new MainPage();
    frame.getContentPane().add(panel);

    frame.pack();
    frame.setVisible(true);
  }
}

其他类别

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class MainPage extends JPanel
    {
        //declare GUI elements
        private JLabel subjectLabel, cHoursLabel, gradeLabel;       
        private JTextField subject, cHours;
        private JButton addSubjectButton, calcGPAButton, clearAllButton;
        private JTextArea tArea;
        private JComboBox grade;

        //declare array to store and collect user input value
        String[] subjectArray = new String[6];                  
        String[] gradeArray = new String[6];
        int[] cHoursArray = new int[6];
        double[] gradeValue = { 4.00, 3.67, 3.33, 3.00, 2.67, 2.33, 2.00, 1.67, 1.33, 1.00, 0.00 };
        String[] gradeLetter= { "A",  "A-", "B+", "B",  "B-", "C+", "C",  "D",  "D-", "E",  "F"};                  


        public MainPage()
        {   
            setLayout (null);
            setPreferredSize (new Dimension(500, 500));
            setBackground (Color.orange); 

            //Properties of GUI elements
            subjectLabel = new JLabel ("Subject Name: ");                       
            subject = new JTextField (33);
            subject.addActionListener (new TempListener());

            gradeLabel = new JLabel ("Grade: ");
            grade = new JComboBox (gradeLetter); 
            grade.addActionListener (new TempListener());

            cHoursLabel = new JLabel ("Credit Hours: ");
            cHours = new JTextField (1);
            cHours.addActionListener (new TempListener());

            addSubjectButton = new JButton("Add Another Subject");
            addSubjectButton.addActionListener(new TempListener());
            calcGPAButton = new JButton("Calculate GPA");
            calcGPAButton.addActionListener(new TempListener());
            clearAllButton = new JButton("Clear All");
            clearAllButton.addActionListener(new TempListener());

            tArea = new JTextArea(5, 5);                
            tArea.setEditable(false);     

            add (subjectLabel);
            add (subject);
            add (gradeLabel);
            add (grade);
            add (cHoursLabel);
            add (cHours);
            add (addSubjectButton);
            add (calcGPAButton);
            add (clearAllButton);
            add (tArea);

            //Position of GUI elements
            subjectLabel.setBounds      (20, 20, 150, 20);              
            subject.setBounds           (120, 20, 350, 20);
            gradeLabel.setBounds        (20, 50, 50, 20);
            grade.setBounds             (120, 50, 50, 20);
            cHoursLabel.setBounds       (20, 80, 100, 20);
            cHours.setBounds            (120, 80, 50, 20);
            addSubjectButton.setBounds  (20, 120, 200, 30);
            calcGPAButton.setBounds     (300, 440, 175, 30);
            clearAllButton.setBounds    (20, 440, 120, 30);
            tArea.setBounds             (20, 170, 450, 250); 
        }


        private class TempListener implements ActionListener
        {
          //---------------------------------------------------------------------------
          //  Performs the conversion when the enter key is pressed in the text field.
          //---------------------------------------------------------------------------
            double tCrPoints = 0.00, tCrHours = 0.00, tGPA = 0.00;  
            String status; 

            public void actionPerformed(ActionEvent event)
            {
                if (event.getSource() == addSubjectButton)                   
                {
                    for (int i=0; i<6; i++)
                    {
                        subjectArray[i] = subject.getText();
                        gradeArray[i] = (String) grade.getSelectedItem();
                        cHoursArray[i] = Integer.parseInt(cHours.getText()); 
                    }

                    tArea.append (subject.getText() + "\t\t\t" + 
                                  grade.getSelectedItem() + "\t"  + 
                                  cHours.getText() + "\n"); 
                    subject.setText("");
                    cHours.setText(""); 
                }


                if (event.getSource() == calcGPAButton)   
                {
                    for (int i=0 ; i<gradeArray.length; i++)
                    {
                        for (int j=0; j<gradeLetter.length; j++)
                        {
                            if(gradeArray[i].equals(gradeLetter[j]))
                            {
                                tCrHours += cHoursArray[i]; 
                                tCrPoints += gradeValue[j] * cHoursArray[i];
                            }
                        }
                    }

                    tGPA = tCrPoints/tCrHours;

                    if (tGPA >= 2)
                        status = ("Pass");
                    else
                        status = ("Fail"); 

                    //Output for text area 
                    tArea.setText("Total Credit Points : " + tCrPoints + "\n" +
                                  "Total Credit Hours : " + tCrHours + "\n\n" + 
                                  "Grade Point Average (GPA) : " + tGPA + "\n" +
                                  "Status : " + status); 
                } 


                if (event.getSource() == clearAllButton)  
                {
                    tArea.setText("");
                    cHours.setText("");
                    grade.setSelectedIndex(0);
                    tCrHours = 0.00;
                    tCrPoints = 0.00;
                }


           }





        }
    }

4 个答案:

答案 0 :(得分:3)

您正在寻找ArrayList<E>

答案 1 :(得分:3)

你很好地将main()从GUI和应用程序的其余部分分开,但我认为你应该进一步将GUI从计算代码中分离出来。

考虑一个更大的问题:为什么GUI JPanel知道成绩和GPA? JPanel的工作是知道如何在框中呈现GUI元素并将输入事件路由到正确的窗口小部件对象。

我相信如果你拆分代码来管理代码中的等级来处理GUI,你的代码将更易于维护并且更具有可塑性。告诉GUI将值更新为model与模型从GUI中轮询数据值之间总是会有一点粗略的优势,但您可以定义该界面以最好​​地满足您的需求:可能是一个GPA对象,使用SLaks's recommended ArrayList<E>来存储知道姓名,成绩,课程日期等的个别Subject个对象。(可能只是(name },grade)元组,因为到目前为止它很短而且很甜。)

您的GPA对象可以导出界面:public void addSubject(String className, String grade)public double getGPA()。您的GUI可以调用此界面来添加新类并检索GPA以供显示。

我意识到这是一个比你想要的更剧烈的重写。它甚至没有立即解决您的问题。但我相信,GPA代码在单独查看时,看起来比目前埋在GUI代码中的代码更容易被操纵。

答案 2 :(得分:2)

您应该查看ArrayListVector甚至LinkedList以了解您所寻求的功能。这是一个tutorial,解释了如何使用ArrayList

这个想法很简单:ArrayList将负责增加一个内部数组来存储它的元素,当你不断添加元素时,它会自动增长以适应它们。严格来说,大小不会无限,但最多2 ^ 31-1个位置(假设你有足够的内存),对于大多数实际情况来说,我应该绰绰有余。

编辑:

对于您的特定示例:

// create an ArrayList
ArrayList<Double> gradeValue = new ArrayList<Double>();

// add elements to the ArrayList
gradeValue.add(4.00);
gradeValue.add(3.67); // etc.

// iterating over the ArrayList
for (int i = 0; i < gradeValue.size(); i++) {
    double value = gradeValue.get(i);
    // etc.
}

答案 3 :(得分:1)

使用散列图包含所有成绩,并使用数组列表来包含您获得的小时和成绩。这是对你所拥有的内容的快速重写。

public class MainPage extends JPanel {

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

private JLabel subjectLabel, cHoursLabel, gradeLabel;      
private JTextField subject, cHours;
private JButton addSubjectButton, calcGPAButton, clearAllButton;
private JTextArea tArea;
private JComboBox grade;

List<String> gradeArray = new ArrayList<String>();
List<Integer> cHoursArray = new ArrayList<Integer>();
Map<String, Double> grades = new HashMap<String, Double>();

public MainPage() {
    this.populateGrades();

    setLayout(null);
    setPreferredSize (new Dimension(500, 500));
    setBackground (Color.orange);

    subjectLabel = new JLabel ("Subject Name: ");
    subject = new JTextField (33);
    subject.addActionListener (new TempListener());

    gradeLabel = new JLabel ("Grade: ");
    grade = new JComboBox (grades.keySet().toArray()); 
    grade.addActionListener (new TempListener());

    // ... THE REST OF YOU CODE ... //
}

private void populateGrades() {
    grades.put("A", 4.00);
    grades.put("A-", 3.67);
    grades.put("B+", 3.67);
    grades.put("B", 3.67);
    grades.put("B-", 3.67);
    grades.put("C+", 3.67);
    grades.put("C", 3.67);
    grades.put("D", 3.67);
    grades.put("D-", 3.67);
    grades.put("E", 3.67);
    grades.put("F", 3.67);
}

private class TempListener implements ActionListener {
    double tCrPoints = 0.00, tCrHours = 0.00, tGPA = 0.00;
    String status;

    public void actionPerformed(ActionEvent event) {
        if (event.getSource() == addSubjectButton) {
            // Not sure what you are trying to do here, you are basically setting the 3 arrays identical
            // subject.getText() = 1 ==> subjectArray[1,1,1,1,1,1]
            // Do not see the point of this at all
            /* for (int i=0; i<6; i++) {
                subjectArray[i] = subject.getText();
                gradeArray[i] = (String) grade.getSelectedItem();
                cHoursArray[i] = Integer.parseInt(cHours.getText());
            } */

            gradeArray.add(grade.getSelectedItem().toString());
            cHoursArray.add(Integer.parseInt(cHours.getText()));

            tArea.append (subject.getText() + "\t\t\t" + grade.getSelectedItem() + "\t"  + cHours.getText() + "\n");
            subject.setText("");
            cHours.setText("");
        }

        if (event.getSource() == calcGPAButton) {
            for (String grade : gradeArray) {
                tCrPoints += grades.get(grade);
            }

            for (Integer hour : cHoursArray) {
                tCrHours += hour;
            }

            tGPA = tCrPoints/tCrHours;

            if (tGPA >= 2) {
                status = ("Pass");
            } else {
                status = ("Fail");
            }

            tArea.setText("Total Credit Points : " + tCrPoints + "\n" +
                        "Total Credit Hours : " + tCrHours + "\n\n" +
                        "Grade Point Average (GPA) : " + tGPA + "\n" +
                        "Status : " + status);
        }

        if (event.getSource() == clearAllButton) {
            tArea.setText("");
            cHours.setText("");
            grade.setSelectedIndex(0);
            tCrHours = 0.00;
            tCrPoints = 0.00;
        }
    }
}
}