本文介绍了使用Java Swing平均成绩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一份我编写的家庭作业。我以为我已经完成了它,但每当我想显示平均值时,它会在内容窗格中显示0的列表。

I have a homework assignment that I have been coding away at. I thought I had it done but whenever I want to display the average it shows a list of 0's in the content pane.

这是作业的描述。

输入成绩后,内容窗格应显示从最低到最高排序的等级
。编写一个遍历
数组的循环,查找大于零(0)的元素。保留这些物品的
运行计数,并将它们累积到
总额中。将总计除以输入的等级数来平均找到
,并显示
等级排序列表末尾的平均值。使用DecimalFormat方法将平均值显示为2
小数位。

After the grades are entered, a content pane should display the grades sorted from lowest to highest. Write a loop that goes through the array looking for elements that are greater than zero (0). Keep a running count of those items, and also accumulate them into a grand total. Divide the grand total by the number of grades entered to find an average, and display the average at the end of the sorted list of grades. Use the DecimalFormat method to display the average to 2 decimal places.



/*
    Chapter 7:      Average of grades
    Programmer:
    Date:
    Filename:       Averages.java
    Purpose:        To use the Java Swing interface to calculate the average of up to 50 grades.
                    Average is calculated once -1 is entered as a value. The grades are then sorted
                    from lowest to highest and displayed in a content pane which also displayes the average.
*/

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

public class Averages extends JFrame
{
    //construct conponents
    static JLabel title = new JLabel("Average of Grades");
    static JTextPane textPane = new JTextPane();
    static int numberOfGrades = 0;
    static int total = 0;
    static DecimalFormat twoDigits = new DecimalFormat ("##0.00");

    //set array
    static int[] grades = new int[50];

    //create content pane
    public Container createContentPane()
    {
        //create JTextPane and center panel
        JPanel northPanel = new JPanel();
        northPanel.setLayout(new FlowLayout());
        northPanel.add(title);

        JPanel centerPanel = new JPanel();
        textPane = addTextToPane();
        JScrollPane scrollPane = new JScrollPane(textPane);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            scrollPane.setPreferredSize(new Dimension(500,200));
        centerPanel.add(scrollPane);

        //create Container and set attributes
        Container c = getContentPane();
            c.setLayout(new BorderLayout(10,10));
            c.add(northPanel,BorderLayout.NORTH);
            c.add(centerPanel,BorderLayout.CENTER);

        return c;
    }

    //method to add new text to JTextPane
    public static JTextPane addTextToPane()
    {
        Document doc = textPane.getDocument();
        try
        {
            // clear previous text
            doc.remove(0,doc.getLength());

            //insert title
            doc.insertString(0,"Grades\n",textPane.getStyle("large"));

            //insert grades and calculate average
            for(int j=0; j<grades.length; j++)
            {
                doc.insertString(doc.getLength(), grades[j] + "\n", textPane.getStyle("large"));
            }
        }
        catch(BadLocationException ble)
        {
            System.err.println("Couldn't insert text");
        }

        return textPane;
    }

    //method to sort array
    public void grades(int grdArray[])
    {
        //sort int array
        for (int pass = 1; pass<grdArray.length; pass++)
        {
            for (int element = 0; element<grdArray.length -1; element++)
            {
                swap(grades, element, element + 1);

            }
        }
            addTextToPane();

    }


    //method to swap elements of array
    public void swap(int swapArray[], int first, int second)
    {
        int hold;
        hold = swapArray[first];
        swapArray[first] = swapArray[second];
        swapArray[second] = hold;
    }

    //execute method at run time
    public static void main(String args[])
    {
        JFrame.setDefaultLookAndFeelDecorated(true);
        Averages f = new Averages();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        //accept first grade
        int integerInput = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter a grade (0-100) or -1 to calculate the average"));

        //while loop accepts more grades, keeps count, and calulates the total
        int count = 0;
        int[] grades = new int[50];
        int num = 0;
        while (count<50 && num!= -1)
        {
            num = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter a grade (0-100) or -1 to calculate the average" + (count+1)));
            if(num!=-1)
                grades[count] = num;
            count++;

        }

        //create content pane
        f.setContentPane(f.createContentPane());
        f.setSize(600,375);
        f.setVisible(true);


    }
}


推荐答案

请解决问题。

从统计数据开始:

/**
 * Statistics
 * @author Michael
 * @link http://stackoverflow.com/questions/15626262/averaging-grades-using-java-swing?noredirect=1#comment22167503_15626262
 * @since 3/25/13 7:50 PM
 */
public class Statistics {
    public static double getAverage(int numValues, int [] values) {
        double average = 0.0;
        if ((values != null) && (numValues > 0) && (values.length >= numValues)) {
            for (int i = 0; i < numValues; ++i) {
                average += values[i];
            }
            average /= numValues;
        }
        return average;
    }
}

接下来我建议你让Swing离开它总共一会儿。做一个纯文本输入/输出UI。

Next I'd recommend that you leave Swing out of it altogether for a little while. Do a text-only input/output UI.

import java.util.Scanner;



/**
 * StatisticsDriver
 * @author Michael
 * @link http://stackoverflow.com/questions/15626262/averaging-grades-using-java-swing?noredirect=1#comment22167503_15626262
 * @since 3/25/13 7:50 PM
 */
public class StatisticsDriver {
    public static final int MAX_VALUES = 50;

    public static void main(String [] args) {
        int [] values = new int[MAX_VALUES];
        Scanner scanner = new Scanner(System.in);
        boolean getAnotherValue;
        int numValues = 0;
        do {
            System.out.print("next value: ");
            String input = scanner.nextLine();
            if (input != null) {
                values[numValues++] = Integer.valueOf(input.trim());
            }
            System.out.print("another? [y/n]: ");
            input = scanner.nextLine();
            getAnotherValue = "y".equalsIgnoreCase(input);
        } while (getAnotherValue);
        System.out.println(Statistics.getAverage(numValues, values));
    }
}

现在有了这些,请将注意力转向Swing 。

Now that you have those, turn your attention to Swing.

在解决问题之前,太多的年轻程序员在Swing上缠绕在轴上。不要犯那个错误。

Too many young programmers get themselves wound around the axle on Swing before they solve the problem. Don't make that mistake.

这篇关于使用Java Swing平均成绩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 12:16