-4

宿題があり、それをコーディングしています。完了したと思いましたが、平均を表示したいときはいつでも、コンテンツペインに0のリストが表示されます.

課題の説明はこちら。

最大長 50 の成績の空の配列を宣言する Swing プログラムを作成します。while ループ内に JOptionPane 入力ボックスを実装して、ユーザーが成績を入力できるようにします。ユーザーがセンチネル値 -1 を入力すると、データ入力ループの終了が通知されます。

成績が入力されると、コンテンツ ペインに最低から最高の順に並べ替えられた成績が表示されます。ゼロ (0) より大きい要素を探して配列を通過するループを作成します。それらのアイテムの実行中のカウントを保持し、それらを合計して合計します。総計を入力された成績の数で割って平均を求め、並べ替えられた成績のリストの最後に平均を表示します。DecimalFormat メソッドを使用して、平均を小数点以下 2 桁まで表示します。

/*
    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);


    }
}
4

3 に答える 3

1

問題を分解してください。

統計から始めます。

/**
 * 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 を実行します。

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 に注意を向けます。

問題を解決する前に、あまりにも多くの若いプログラマーが Swing の軸に巻き付いてしまいます。その間違いをしないでください。

于 2013-03-25T23:59:30.957 に答える
0

grades配列が 2 回宣言されています。1 回目は内でローカルにmain()、2 回目はグローバルに。ユーザーに成績を入力するように求めるときは、さまざまな位置を 内の配列に割り当てますmain()。ただし、 で情報を取得するときはaddTextToPane()、グローバルに宣言されたgrades配列を呼び出します。

で以下を削除するmain()と、問題は解決します。

int[] grades = new int[50];

于 2013-03-25T22:54:44.373 に答える
0

さて、私が見ることができるよりも最初の間違いはこれです:

メインの静的配列グレードが隠されています

int[] 成績 = 新しい int[50];

于 2013-03-25T23:01:25.537 に答える