Good Day, I am also a newby to the JAVA world of developing. I am SERIOUSLY struggling with a homework assignment ... I have a swing program that is using a JFrame and the task is to calculate the average grade. First, a JOptionPane needs to be used to get the input from the user. (This i did with the String strGrades). The sentinal -1 stops the input from the user side. (I parse the strGrades to an int grades, to be able to use the sentinal value in a while loop). Then the grades needs to be entered into a JTextPane, then sorted from low to high and the average calculated. I cannot get the Grades to show in the JTextPane, so I don't know if my calculation or sorting works. I presume my problem lies in the "addTextToJTextPane()" ... especially the "insert detail" part as this is where I am initialising the array, and also the JOptionPane. I am not sure how I can get the int of grades to be used in the string array (called the array grd). I will attach my entire code for any feedback and assistance:

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

public class AverageGrade extends JFrame implements ActionListener
{
	// Construct class variables
	int grades; // grade value
	int gradeCount = 0; // number of grades entered
	int totGrade = 0; // sum of grades
	double avgGrade; // number with decimal point for average
	String strGrades; // string to input grades

	// Construct components
	JTextPane gradesPane = new JTextPane();
	JButton calcGrade = new JButton("Calculate Average");

	// Construct instance of Average Grade
	public AverageGrade()
	{
		super ("Calculating Average Grade");
	}

	// Create Content Pane
	public Container createContentPane()
	{
		//Create JTextPane & centerPanel
		JPanel centerPanel = new JPanel();
			gradesPane = addTextToTextPane();
			JScrollPane scrollPane = new JScrollPane(gradesPane);
				scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
				scrollPane.setPreferredSize(new Dimension(200, 200));
			centerPanel.add(scrollPane);

		// Create southPanel
		JPanel southPanel = new JPanel();
			southPanel.setLayout(new FlowLayout());
			southPanel.add(calcGrade);
			calcGrade.addActionListener(this);

		//Create Container and set attributes
		Container c = getContentPane();
			c.setLayout(new BorderLayout(10,10));
			c.add(centerPanel, BorderLayout.CENTER);
			c.add(southPanel, BorderLayout.SOUTH);

		return c;
	} // end createContentPane()

	//method to set font styles
	protected void setTabsAndStyles(JTextPane gradesPane)
	{
		//set Font Style
		Style myStyle =
			StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);

		Style regular = gradesPane.addStyle("regular", myStyle);
		StyleConstants.setFontFamily(myStyle, "Arial");

		Style s = gradesPane.addStyle("large", regular);
		StyleConstants.setFontSize(s, 12);

	} // end setTabsAndStyles()

	// Add text to JTextPane
	public JTextPane addTextToTextPane()
	{
		// assign text to document object
		Document doc = gradesPane.getDocument();

			try
			{
				//clear previous text
				doc.remove(0, doc.getLength());

				// insert title
				doc.insertString(0, "GRADE", gradesPane.getStyle("large"));

				// insert detail
				while(grades != -1)
				{
					strGrades = JOptionPane.showInputDialog(null, "Please insert Grade");

					if (strGrades == null) finish();

					grades = Integer.parseInt(strGrades);

					totGrade = totGrade + grades; // add grade to total

					gradeCount = gradeCount + 1; // increment counter
				}

				// Initialize array
				String[] grd = new String [50];

				for (int i=0; i<=grades; i++)
				{
					for (int j=0; j<grd.length; j++)
					{
						doc.insertString(doc.getLength(), grd[i] + "\t", gradesPane.getStyle("regular"));
					} // end for loop to insert detail

				} // end for loop to initialize array

			} // end try

			catch (BadLocationException ble)
			{
				System.err.println("Couldn't insert text.");
			} // end catch

		return gradesPane;
	} // end addTextToTextPane()

	// Method to sort Grades from Low to High
	public void sort(String tempArray[])
	{
		// Loop to control number of passes
		for (int pass = 1; pass < tempArray.length; pass++)
		{
			for(int element = 0; element < tempArray.length - 1; element++)
				if (tempArray[element].compareTo(tempArray[element + 1])>0)
				{
					swap(grd, element, element + 1);
				} // end if
		} // end for loop
		addTextToTextPane();
	}  // end sort()

	// Method to swap two elements of an Array
	public void swap(String swapArray[], int first, int second)
	{
		String hold; // temporary holding area for swap
		hold = swapArray[first];
		swapArray[first] = swapArray[second];
		swapArray[second] = hold;
	} // end swap()

	// Action button Calculate
	public void actionPerformed(ActionEvent e)
	{
		String arg = e.getActionCommand();
		if (arg == "Calculate")

		avgGrade = totGrade / gradeCount;
	}

	public static void finish()
	{
		System.exit(0);
	}

	public static void displayGrade(double avgGrade)
	{
		DecimalFormat twoDigits = new DecimalFormat ("###%");
		JOptionPane.showMessageDialog(null, "The Average Grade: " + twoDigits.format(avgGrade));
	}

	//Main method execute at run time
	public static void main(String args[])
	{
		JFrame.setDefaultLookAndFeelDecorated(true);
		AverageGrade f = new AverageGrade();
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setContentPane(f.createContentPane());
		f.setSize(300, 300);
		f.setLocation(200,200);
		f.setVisible(true);
	} // end main()

} // end class

Recommended Answers

All 10 Replies

You have general flaw in the logic. The values collected by JOptionPane will never get out of your while loop. To add the values to array you need to add each new grade to array inside while loop.
Also I would suggest to use ArrayList instead of size limited Array, that way you do not have to worry about exceeding Array limit and always you can convert ArrayList to simple Array with help of API

PS: Above posted code will not compile because you use wrong array

// Method to sort Grades from Low to High
	public void sort(String tempArray[])
	{
		// Loop to control number of passes
		for (int pass = 1; pass < tempArray.length; pass++)
		{
			for(int element = 0; element < tempArray.length - 1; element++)
				if (tempArray[element].compareTo(tempArray[element + 1])>0)
				{
					swap(/*grd*/tempArray, element, element + 1);
				} // end if
		} // end for loop
		addTextToTextPane();
	}  // end sort()
commented: very helpful in this thread... +5

Thank You Peter_budo, that helped quite a lot, I changed the code around just a bit and now at least the text is drawing in to the JTextPane! :icon_biggrin: The only thing, it only draws in null values and not the values the user will enter. But, I am still working on that ... now with more enthusiasm! :) And I have also made the changes you suggested to the Sort. Thank You.

Just to show you what the new code looks like for that part:

// Add text to JTextPane
	public JTextPane addTextToTextPane()
	{
		// assign text to document object
		Document doc = gradesPane.getDocument();

			try
			{
				//clear previous text
				doc.remove(0, doc.getLength());

				// insert title
				doc.insertString(0, "GRADE", gradesPane.getStyle("large"));

				// Insert details
				// Initialize array
				String[] grd = new String [50];

				for (int i=0; i<=grades; i++)
				{
					while(grades != -1)
					{
						strGrades = JOptionPane.showInputDialog(null, "Please insert Grade");

						if (strGrades == null) finish();

						grades = Integer.parseInt(strGrades);

						totGrade = totGrade + grades; // add grade to total

						gradeCount = gradeCount + 1; // increment counter
					}

					for (int j=0; j<grd.length; j++)
					{
						doc.insertString(doc.getLength(), grd[j] + "\t", gradesPane.getStyle("regular"));
					} // end for loop to insert detail

				} // end for loop to initialize array

			} // end try

			catch (BadLocationException ble)
			{
				System.err.println("Couldn't insert text.");
			} // end catch

		return gradesPane;
	} // end addTextToTextPane()
/*Yes you do declare and instantiate  array here*/
	String[] grd = new String [50];

	for (int i=0; i<=grades; i++)
	{
		while(grades != -1)
		{
			/*However do you store data retrieved from user somewhere in this section to array???*/
			strGrades = JOptionPane.showInputDialog(null, "Please insert Grade");

			if (strGrades == null) finish();
				grades = Integer.parseInt(strGrades);
				totGrade = totGrade + grades; // add grade to total

			gradeCount = gradeCount + 1; // increment counter
			/*End of section which I meant*/
		}

		for (int j=0; j<grd.length; j++)
		{
			doc.insertString(doc.getLength(), grd[j] + "\t", gradesPane.getStyle("regular"));
		} // end for loop to insert detail

	} // end for loop to initialize array

Hi Peter, i am trying to store data into the array from the user input, but that is what i am struggling with. When my code compiles now, i only get 50 null values in the JTextPane :( ... I cannot get the data entered by the user to display. How do I get that into the array?

Somewhere in that block that I marked you should have something like grd[i] = SOMETHING; where i represent next available position to be used

PS: You shouled really look into use of Collections like ArrayList as these makes your life easier. No need of size declaration, adding process will either add to end of the ArrayList or in specific position requested by your application logic

I need to get the grd = strGrades ... as the strGrades are getting the values.

Or is there a way I can load the values directly into the String grd[] using JOptionPane?

Correct answer.

Question for you: Are you sure you want to keep read in grades in String format, while you use their integer values for calculations? Wouldn't be better to have Array of integers rather then array of Strings?

As in regards of ArrayList, doesn't this look better

ArrayList<Integer> grd = new ArrayList<Integer>();
while(grades != -1)
{
	strGrades = JOptionPane.showInputDialog(null, "Please insert Grade");

	if (strGrades == null) finish();
		grades = Integer.parseInt(strGrades);
		totGrade = totGrade + grades; // add grade to total

	gradeCount = gradeCount + 1; // increment counter
}

then your limited size array?

Yes, the Arraylist is looking much better, the code is more simplified for me.
Not sure how I am going to do the limit for 50, i have read that i can convert an ArrayList to a normal Array and then perhaps declare an index of 50.

If i use only integer arrays, how am i going to get the data into the JTextPane? I only managed to get the data to show in the JTextPane when I changed the array to String Array.

Yeah sorry forgot you using JTetxPane, keep ArrayList as String

To add element to ArrayList use add(Element) and to convert ArrayList to Array use toArray() method

Hi All, I managed to solve this query of mine! :)
Please see the code of the addTextToTextPane():

// Add text to JTextPane
	public JTextPane addTextToTextPane()
	{
		// assign text to document object
		Document doc = gradesPane.getDocument();

			try
			{
				//clear previous text
				doc.remove(0, doc.getLength());

				// insert title
				doc.insertString(0, "ALL GRADES\n\n", gradesPane.getStyle("large"));

				// Insert details

				int i = 0;

				for(i = 0; i < 50; i++)
				{
					strGrades = JOptionPane.showInputDialog(null, "Please insert Grade");

					if (strGrades == null) finish();

					grades = Integer.parseInt(strGrades);

					if (grades == -1) return gradesPane;

					grd[i] = strGrades;

					doc.insertString(doc.getLength(), grd[i] + "\t", gradesPane.getStyle("regular"));

				} // end for loop to initialize array

			} // end try

			catch (BadLocationException ble)
			{
				System.err.println("Couldn't insert text.");
			} // end catch

		return gradesPane;
	} // end addTextToTextPane()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.