Java GPA calculation (how to set unlimited arrays?) - java

Basically, my problem is that I am not sure on how to set unlimited input arrays from user..
For now, the calculation only goes well if the user enters 6 subject exactly, but not if entered subject is less or more than 6..
Somehow, i want to make the input to be unlimited..
This is what I have so far:
THE MAIN CLASS
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);
}
}
THE OTHER CLASS
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;
}
}
}
}

You're looking for ArrayList<E>

You did a good job splitting apart the main() from the GUI and the rest of the application, but I think you should have taken it further to split the GUI from the calculation code, too.
Consider the larger question: Why does a GUI JPanel know about grades and GPAs? The job of a JPanel is to know how to render GUI elements within a box and route input events to the right widget object.
I believe your code would be far more maintainable and definitely more malleable if you split the code to manage the grades from the code to handle the GUI. There's always going to be a bit of a rough edge between telling the GUI to update values into the model vs having the model poll the data values from the GUI, but you can define that interface to suit your needs best: it might be a GPA object that uses SLaks's recommended ArrayList<E> to store individual Subject objects that know the name, grade, dates the course was conducted, etc. (It might just be (name, grade) tuples, since this is short and sweet so far.)
Your GPA object could export an interface: public void addSubject(String className, String grade) and public double getGPA(). Your GUI could call into this interface to add new classes and retrieve the GPA for display.
I realize that this is a much more drastic re-write than you were looking for. And it doesn't even immediately address your concern. But I believe the GPA code, when viewed on its own, would look far more easily manipulated than it currently does buried amongst the GUI code.

You should look at ArrayList, Vector or even LinkedList for the functionality you seek. Here's a tutorial explaining how to use an ArrayList.
The idea is simple: the ArrayList will take care of growing an internal array for storing its elements, and as you keep adding elements to it, it will keep growing automatically to accommodate them. Strictly speaking, the size won't be unlimited, but a maximum of 2^31-1 positions (assuming that you have enough memory) should me more than enough for most practical cases.
EDIT :
For your particular example:
// 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.
}

Use a hashmap to contain all your grades, and use array lists to contain your hour and grade earned. Here is a quick rewrite of what you have.
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;
}
}
}
}

Related

Custom java calculator troubleshooting

New programmer here, I have been working for a few days on this bit of code that is meant to create a UI where I input a basement's perimeter length (textfield integer), if a new pump is needed (combobox string), if there is an outlet nearby (combobox string), and how many hours It will take to prepare a site (textfield integer), and I calculate my costs to complete a job. I was able to set up a UI where I can enter the inputs and press a button to calculate but I'm having trouble connecting the button I made to the formula I made to generate a price. Here is my code:
package packagepackage;
import packagepackage.HintTextFieldUI;
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CP_GUI implements ActionListener {
String[] sumpo = {"New sump pump","Existing sump pump"};
String[] electo = {"There is an outlet within 6 feet of sump pump","There is no outlet nearby, or I do not need a new one"};
Integer estimatex = 0;
String esto = String.valueOf(estimatex);
public volatile String estimatoof = "Estimated Cost: ${}".format(esto);
private JComboBox sump = new JComboBox(sumpo);
private JComboBox elec = new JComboBox(electo);
private JTextField linear = new JTextField();
private JTextField prep = new JTextField();
private JLabel title = new JLabel("Drain Tile Calculator");
private JButton calculate = new JButton("Calculate!");
public JLabel estimate = new JLabel(estimatoof);
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
public CP_GUI() {
linear.addActionListener(this);
calculate.addActionListener(this);
elec.addActionListener(this);
sump.addActionListener(this);
prep.addActionListener(this);
// the panel with the button and text
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(400, 400, 100, 100));
panel.setLayout(new GridLayout(0, 1));
panel.add(linear);
panel.add(sump);
panel.add(elec);
panel.add(prep);
frame.add(panel, BorderLayout.CENTER);
panel.add(title);
calculate.addActionListener(this);
panel.add(calculate);
// set up the frame and display it
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Drain Tile Calculator");
frame.pack();
frame.setVisible(true);
linear.setUI(new HintTextFieldUI("Perimeter length", true));
prep.setUI(new HintTextFieldUI("Hours of preptime", true));}
// create one Frame
public static void main(String[] args) {
new CP_GUI();
}
#Override
public void actionPerformed(ActionEvent e){
// TODO Auto-generated method stub
if(e.getSource()==linear) {String input = linear.getText();
Integer pars = Integer.parseInt(input);
Integer distVar = pars *= 13;
estimatex += distVar;
} else if (e.getSource()==sump) {String inputa = sump.getToolTipText();
int sumpa = 0;
if(inputa == "New sump pump" | inputa == "yes") {
sumpa += 260;}
estimatex += sumpa;
} else if (e.getSource()==elec) {String inputb =elec.getToolTipText();
int eleca = 0;
if("There is an outlet within 6 feet of the sump pump".equals(inputb)) {
eleca += 1;
}
eleca *= 280;
estimatex += eleca;
}
else if (e.getSource()==prep) {String inputc = prep.getText();
int parsa = Integer.parseInt(inputc);
int prepCost = parsa += 1;
prepCost *= 110;
estimatex += prepCost;
} else if (e.getSource()==linear) {
String disto = linear.getText();
int di = Integer.parseInt(disto);
di *= 13;
String pumpo = (String)sump.getSelectedItem();
int sumpo = 0;
if ("New sump pump".equals(pumpo)) {
sumpo += 260;
}
String ele = (String)elec.getSelectedItem();
int elc = Integer.parseInt(ele);
elc *= 280;
String clea = prep.getText();
int cla = Integer.parseInt(clea);
cla += 1;
cla *= 110;
int cali = 0;
cali += di;
cali += sumpo;
cali += elc;
cali += cla;
estimatex = cali;
}
}
}
Edit: Made the suggested edits made so far and now the UI opens and works, the only issue is that the estimated price does not show up. Am I connecting the action listener correctly?
Your "primary" problem is right here...
String disto = String.valueOf(linear);
where linear is a JTextField, so the above call will generate something like...
javax.swing.JTextField[,0,0,0x0,invalid,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=com.apple.laf.AquaTextFieldBorder#4e323305,flags=288,maximumSize=,minimumSize=,preferredSize=,caretColor=javax.swing.plaf.ColorUIResource[r=0,g=0,b=0],disabledTextColor=javax.swing.plaf.ColorUIResource[r=128,g=128,b=128],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=com.apple.laf.AquaImageFactory$SystemColorProxy[r=0,g=0,b=0],selectionColor=com.apple.laf.AquaImageFactory$SystemColorProxy[r=165,g=205,b=255],columns=0,columnWidth=0,command=,horizontalAlignment=LEADING]
which is obviously not what you're looking for.
You should probably be just doing something like...
String disto = linear.getText();
pumpo == "New sump pump" is also not how you compare a String in Java, you should be using "New sump pump".equals(pumpo) ... but I suspect you're going to have the same issues as mentioned above.
I really recommend you take the time to read through Creating a GUI With Swing as well as taking the time to come to grips with the core basics of the language

Issues with GUI on a permutation/combination calculator

I was able to program this, and I don't have any errors that I can see, and it even displays the gui. I'm pretty sure I assigned the buttons properly. But the GUI is temperamental, and when I run it, it displays but sometimes the insides of the gui disappear when I enter values. But it calculates nCr, just not pCr.
I have a driver class. Pretty sure it's implemented properly. Here's my panel class. I'm wondering what's wrong and why the GUI doesn't function properly
I realize this is a lot of code. I'm not expecting anyone to rewrite this for me. I just want to know what I'm doing wrong, and how I can go about correcting it.
Thanks.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Color;
import javax.swing.JOptionPane;
public class PermCombCalc extends JPanel {
JButton permButton = new JButton();
JButton combButton = new JButton();
JButton clearButton = new JButton();
JTextField npermField = new JTextField();
JTextField rperField = new JTextField();
JTextField nchooseField = new JTextField();
JTextField rchooseField = new JTextField();
JTextField pAnswerField = new JTextField();
JTextField cAnswerField = new JTextField();
public PermCombCalc() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(1000, 700));
JLabel permLabel = new JLabel("Permutation:");
permLabel.setBounds(10, 20, 100, 20);
permLabel.setForeground(Color.BLACK);
add(permLabel);
JLabel combLabel = new JLabel("Combination:");
combLabel.setBounds(215, 20, 75, 20);
combLabel.setForeground(Color.BLACK);
add(combLabel);
// Creating Permutation Button
JLabel PnrLabel = new JLabel("P (n,r)");
PnrLabel.setForeground(Color.black);
permButton.setBounds(10, 115, 100, 25);
add(permButton);
permButton.add(PnrLabel);
// Action Listener for permbutton
permButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
permButton.setActionCommand("Perm");
permButton.addActionListener(new ButtonListener());
}
});
// Creating combination button
JLabel CnrLabel = new JLabel("C(n, r)");
CnrLabel.setForeground(Color.black);
combButton.setBounds(190, 115, 100, 25);
add(combButton);
combButton.add(CnrLabel);
// ActionListener
combButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
combButton.setActionCommand("comb");
combButton.addActionListener(new ButtonListener());
}
});
// Text fields for n and r
npermField.setBounds(23, 50, 60, 20);
add(npermField);
nchooseField.setBounds(230, 50, 60, 20);
add(nchooseField);
rperField.setBounds(23, 80, 60, 20);
add(rperField);
rchooseField.setBounds(230, 80, 60, 20);
add(rchooseField);
// Input fields
JLabel npLabel = new JLabel("n:");
npLabel.setForeground(Color.black);
npLabel.setBounds(10, 55, 10, 10);
add(npLabel);
JLabel ncLabel = new JLabel("n:");
ncLabel.setForeground(Color.BLACK);
ncLabel.setBounds(217, 55, 10, 10);
add(ncLabel);
JLabel rpLabel = new JLabel("r:");
rpLabel.setForeground(Color.BLACK);
rpLabel.setBounds(10, 85, 10, 10);
add(rpLabel);
JLabel rcLabel = new JLabel("r:");
rcLabel.setForeground(Color.BLACK);
rcLabel.setBounds(217, 85, 10, 10);
add(rcLabel);
// Fields for answers
JLabel pAnswerJLabel = new JLabel("<-Answers->");
pAnswerJLabel.setForeground(Color.BLACK);
pAnswerJLabel.setBounds(115, 155, 74, 10);
add(pAnswerJLabel);
pAnswerField.setBounds(10, 150, 100, 20);
add(pAnswerField);
cAnswerField.setBounds(190, 150, 100, 20); // where is this field?!
add(cAnswerField);
// Buttons
//clearButton.setBounds(10, 210, 110, 25);
//add(clearButton);
//JLabel clearLabel = new JLabel("Clear Fields");
//clearLabel.setForeground(Color.BLACK);
//clearButton.add(clearLabel);
// clearButton.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// clearButton.setActionCommand("Clear");
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("perm")) {
// contentPane.setBackground(Color.red);
long Pnr = Permutation();
if (Pnr != 0) {
pAnswerField.setText(Pnr + "");
}
} else if (e.getActionCommand().equals("comb")) {
// contentPane.setBackground(Color.black);
long Cnr = Combination();
if (Cnr != 0) {
cAnswerField.setText(Cnr + "");
}
} else if (e.getActionCommand().equals("Clear")) {
// contentPane.setBackground(Color.lightGray);
npermField.setText(null);
rperField.setText(null);
pAnswerField.setText(null);
nchooseField.setText(null);
rchooseField.setText(null);
cAnswerField.setText(null);
}
}
public long Permutation() {
String npString = npermField.getText();
String rpString = rperField.getText();
int npint = 0;
int rpint = 0;
try {
npint = Integer.parseInt(npString);
rpint = Integer.parseInt(rpString);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,"ERROR! The values for 'n' and 'r' \n must be positive integers");
return 0;
}
if (npint <= 0 || rpint <= 0) {
JOptionPane.showMessageDialog(null,"ERROR! The values for 'n' and 'r' \n must be positive integers");
return 0;
}
if (npint < rpint) {
JOptionPane.showMessageDialog(null,"ERROR! The value of 'r' must be less than \n or equal to the value of 'n.'");
return 0;
}
long Pnr = 1;
int mult = npint;
int nmr = (npint - rpint);
while (mult > nmr) {
Pnr = Pnr * mult;
mult--;
}
return Pnr;
}
public long Combination() {
String ncString = nchooseField.getText();
String rcString = rchooseField.getText();
int ncint = 0;
int rcint = 0;
try {
ncint = Integer.parseInt(ncString);
rcint = Integer.parseInt(rcString);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,"ERROR! The values for 'n' and 'r' \n must be positive integers");
return 0;
}
if (ncint <= 0 || rcint <= 0) {
JOptionPane.showMessageDialog(null,"Error! The values for 'n' and 'r' \n must be positive integers");
return 0;
}
if (ncint < rcint) {
JOptionPane.showMessageDialog(null,"ERROR! The value of 'r' must be less than \n or equal to the value of 'n.'");
return 0;
}
long nfact = 1;
for (int i = 2; i <= ncint; i++) {
nfact = nfact * i;
}
long rfact = 1;
for (int i = 2; i <= rcint; i++) {
rfact = rfact * i;
}
long nmr = ncint - rcint;
int nmrfact = 1;
for (int i = 2; i <= nmr; i++) {
nmrfact = nmrfact * i;
}
long Cnr = (nfact / (rfact * nmrfact));
return Cnr;
}
}
}
You are using BorderLayout, but you aren't actually specifying the placements of your components, so they are being rendered in unexpected places.
Here is a screenshot of your application with an orange border around pAnswerField and a red border around cAnswerField
You should take a look at the A Visual Guide to Layout Managers for help on using the Layout Managers properly.
For your application, GridLayout is probably a resonable balance between complexity and layout flexibility
GridBagLayout or SpringLayout will give you the most flexibility, but they can be frustratingly complex to work with.
EDIT Another minor problem which is causing the permButton to misbehave.
In your button creation code you have:
permButton.setActionCommand("Perm");
In your action listener you have: if (e.getActionCommand().equals("perm"))
As written your ActionListener will never get invoked when permButton gets pressed... Either switch to equalsIgnoreCase or define a constant rather than using string literals.
I find adding colored borders to be very helpful when doing layout work. Here's a quick example of how to do this:
npermField.setBounds(23, 50, 60, 20);
add(npermField);
nchooseField.setBounds(230, 50, 60, 20);
// add a border to make the component easier to see during layout.
npermField.setBorder(BorderFactory.createLineBorder(Color.ORANGE));
add(nchooseField);
If you like your ButtonListener class the way it is (I don't; will comment about it after the main issue), you can simply reword the buttons' setup:
.
.
.
add(permButton);
permButton.add(PnrLabel);
// Action Listener for permbutton
permButton.setActionCommand("Perm");
permButton.addActionListener(new ButtonListener());
.
.
.
(and likewise for the other buttons).
See? There is no need to add an ActionListener more than once AND also no need to add an ActionListener in order to add the real ActionListener.
The way your application was:
it didn't work on the first button press (since only then the correct listener is set up);
after the first button press, each new press would add another listener, eventually producing unexpected results (I didn't analyzed it thoroughly, and frankly I will not).
About the ButtonListener
Roughly speaking, your class does:
if (typeA) {
doActionA();
} else if (typeB) {
doActionB();
} else if (typeC) {
doActionC();
}
You could simply create 3 separate ActionListeners, each doing just one thing (either doActionA(), or B or C), without ifs. Then set up each button with only the appropriate ActionListener. This way you could also remove the lines setActionCommand(type);, since they would become useless.

Java NPE with .split

I'm fairly new with Java, (and this site) so I'm not sure what to do with this "issue"...
I'm not sure whether to put my entire code in this or not...So I'll just put what I think is causing the issue. The program compiles perfectly, except when I try to run it. That's when I get a Null Pointer Exception at line 96. I have no idea why this is happening.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class LicensePlateGeneratorTemplate extends JFrame implements ActionListener{
private JTextArea txtOutput;
private JTextField txtNumPlates;
private JButton btnDisplay;
private JLabel lblTitle, lblInstruction;
private PrintWriter output;
private String letters, numbers, fileName;
private int randomLetter, randomNumber, numPlates;
private String [] a, b ;
private String [] lttrArray, nmbrArray;
public static void main(String[] args) throws IOException{
new LicensePlateGeneratorTemplate();
}
public LicensePlateGeneratorTemplate() throws IOException{
//label thast contains number of licence plates generated
txtNumPlates = new JTextField();
txtNumPlates.setBounds(320, 60, 28, 28);
lblInstruction = new JLabel("How many license plates would you like to generate?");
lblInstruction.setBounds(15, 60, 300, 28);
//A random number generator in the action performed method should allow you to select a random letter from the letters String
//then a random number from the numbers String
String letters = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Z";
String numbers = "1,2,3,4,5,6,7,8,9,0";
lttrArray = letters.split (",");
nmbrArray = numbers.split (",");
System.out.println(lttrArray[20] + lttrArray [10]);
System.out.println(nmbrArray[3]+ nmbrArray [5]);
fileName = "licensePlates.txt";
output = new PrintWriter(new FileWriter(fileName));
lblTitle = new JLabel();
lblTitle.setFont(new Font("Britannic Bold", Font.BOLD, 28));
lblTitle.setText("License Plate Generator");
lblTitle.setBounds(30, 10, 400, 50);
JPanel panel = new JPanel();
panel.setLayout(null);
//JTextArea
txtOutput = new JTextArea();
txtOutput.setBounds(60, 150, 275, 196);
txtOutput.setEditable(true);
//generate button properties
btnDisplay = new JButton();
btnDisplay.setText("Generate");
btnDisplay.setBounds(150, 100, 100, 40);
btnDisplay.setFocusable(true);
btnDisplay.addActionListener(this);
//add components to the panel
panel.add(btnDisplay);
panel.add(txtOutput);
panel.add(lblTitle);
panel.add(lblInstruction);
panel.add(txtNumPlates);
//frame properties
setContentPane(panel);
setSize(400, 400);
setTitle("License Plate Generator");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
public void actionPerformed (ActionEvent e)
{
if (e.getSource() == btnDisplay)
{
//change number user inputs into a int value
int userNum = Integer.parseInt(txtNumPlates.getText ());
for (int k = 0; k <= userNum; k ++)
{//number of licence places that are being made
for (int i = 0; i < 4; i ++)//loop for letters produced
{
int randLtr = 0 + (int)(Math.random() * ((24 - 0) + 1));
a [i] = lttrArray [randLtr];
output.println (a[i]);
txtOutput.insert(a[i] + "\n", 0);
}
for (int j = 0; j < 3; j++)//loop for number produced
{
int randNum = 0 + (int)(Math.random() * ((9 - 0) + 1));
b [j] = nmbrArray [randNum];
output.println (b[j]);
txtOutput.insert(b[j] + "\n", 0);
}
output.close();//closes fileWriter
}//end of userNum loop
}//end of e.getsource
}
}
Edit: Added full code.
Since lttrArray is clearly non-null (unless you're assigning it as lttrArray = null somewhere in the snipped code), I would guess that a is null.

for loop for array only processing one element in java?

I can't figure out why whenever I cycle through my array using the for-loop it only produces one element (the first) to console? I'm pretty sure it's a rookie-mistake I'm looking over, so any tips and suggestions would help.
I'm making a program for fun that compares two strings typed in a text field and if they don't exist in the array it produces a JOPtionPane message on the contrary. It's for a battle-hack I may produce in the future for vBulletin forum, but I'm messing around with algorithms before I move to that step. Thanks, guys!
package battleoptionspart1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.lang.*;
import javax.swing.border.*;
public class BattleOptionsPart1 extends JFrame{
JButton newthread, previewpost;
JRadioButton battle1;
JTextField postcount, oppA, oppB;
JLabel battle2, max;
JPanel panel;
String [] array = {"Bill","Tom","Wendy", "Paula"};
public BattleOptionsPart1 () {
panel = new JPanel();
Toolkit tool = Toolkit.getDefaultToolkit();
Dimension dim = tool.getScreenSize();
this.setSize(500, 500);
this.setTitle("Battle Options");
GridLayout grid = new GridLayout(0,1,2,2);
this.setLayout(grid);
newthread = new JButton("Post New Thread");
previewpost = new JButton("Preview Post");
postcount = new JTextField("", 4);
oppA = new JTextField("",10);
oppB = new JTextField("",10);
battle1 = new JRadioButton();
battle2 = new JLabel("Would you like to start a recorded battle?");
max = new JLabel("Enter max post count user must have to vote");
ListenForButton listen = new ListenForButton();
newthread.addActionListener(listen);
previewpost.addActionListener(listen);
JPanel opponents = new JPanel();
Border oppBorder = BorderFactory.createTitledBorder("Battlers");
opponents.setBorder(oppBorder);
opponents.add(oppA);
opponents.add(oppB);
JPanel battle = new JPanel();
Border battleBorder = BorderFactory.createTitledBorder("Start Battle");
battle.setBorder(battleBorder);
battle.add(battle1);
battle.add(battle2);
JPanel buttons = new JPanel();
Border buttonBorder = BorderFactory.createTitledBorder("Create Thread");
buttons.setBorder(buttonBorder);
buttons.add(newthread);
buttons.add(previewpost);
JPanel restriction = new JPanel();
Border resBorder = BorderFactory.createTitledBorder("Restrictions");
restriction.setBorder(buttonBorder);
restriction.add(postcount);
restriction.add(max);
this.add(opponents);
this.add(battle);
this.add(restriction);
this.add(buttons);
this.add(panel);
int xPos = (dim.width / 2) - (this.getWidth() / 2);
int yPos = (dim.height / 2) - (this.getHeight() / 2);
this.setLocation(xPos,yPos); //places form in the middle
this.setVisible(true); // users can see form
this.setResizable(false); //users can't resize the form
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class ListenForButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String compareA = oppA.getText();
String compareB = oppB.getText();
if (e.getSource() == newthread)
{
System.out.println(compareA + "\n" + compareB);
for(int j = 0; j < array.length; j++)
{
System.out.println(array[j]);
if(!compareA.equals(array[j]))
{
JOptionPane.showMessageDialog(null, compareA + " doesn't exist!", "Error Message", JOptionPane.ERROR_MESSAGE);
oppA.requestFocus();
break;
}
if (!compareB.equals(array[j]))
{
JOptionPane.showMessageDialog(null, compareB + " doesn't exist!", "Error Message", JOptionPane.ERROR_MESSAGE);
oppB.requestFocus();
break;
}
else
{
JOptionPane.showMessageDialog(null, "New thread created successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}
else if (e.getSource() == previewpost)
{
System.exit(0);
}
}
}
public static void main(String[] args) {
BattleOptionsPart1 battle = new BattleOptionsPart1();
}
}
In each of the possible options in your loop, you use break, which leaves the loop immediately. If you remove those statements, you'll process each object in the array.
If you want to check if there's a match, you need to go through every element and do your processing after going through the whole array. Here is an example for an array of type int:
boolean contains = false;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == searchKey)
{
contains = true;
break;
}
}
You're breaking out of the loop. with the break; command after the first array element

My Answer keep Returning Wrong after First input and wont keep track of score?

I trying to make a math quiz game that generates random question and keep track of of what question are wrong and write.
got action listener to work but when i type in a answer it say my answer is wrong, even though it right. the first question that appear work fine but after that it , it say all my answer are wrong even though they are right and keep track of score.
import java.util.Scanner;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.util.Random;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class PracticeMath extends JFrame implements ActionListener {
Scanner k = new Scanner(System.in);
Random generator = new Random();
protected JButton excerciseButton = new JButton( "New Excerices" ); // start new quiz session
protected JButton answerButton = new JButton( "Answer" ); // set new question, check if the answer correct or wrong
protected JLabel titlelabel = new JLabel( "How much is: " );
protected int correctcounter = 0; // keep track of correct answer
protected int wrongcounter = 0; // keep track of wrong answer
protected int one = generator.nextInt(10);//generate ranodm first number of question
protected int two = generator.nextInt(10); // generate random second number of question
protected int i = generator.nextInt(4); // generate random operator
protected char[] ops = { '+', '-', '/', '*' }; // the math operator
protected JLabel correctlabel = new JLabel(" Number of Correct Answer: ");
protected JLabel wronglabel = new JLabel( " Number of Wrong answers: " );
protected JLabel firstnum = new JLabel("" + one); // display first number
protected JLabel secondnum = new JLabel("" + two); // display second number
protected JLabel randomOP = new JLabel("" + ops[i]); // display operator
protected JLabel equalOP = new JLabel("=");
protected JTextField answerText = new JTextField(); //text area for writing you answer
protected JLabel questionmark = new JLabel("?");
protected JLabel correct = new JLabel(""+ correctcounter); // display correct answer
protected JLabel wrong = new JLabel(""+ wrongcounter); // display wrong answer
protected JLabel commentlabel = new JLabel(""); // set a comment for how good you doing. optionial
public PracticeMath(){
answerText.setColumns(5);
JPanel Panel1 = new JPanel();// add a panel
FlowLayout flowLayout = (FlowLayout) Panel1.getLayout();// layout for panel
getContentPane().setLayout( new FlowLayout( FlowLayout.LEFT, 5, 5)); // set layout
getContentPane().add(Panel1); // set panel
titlelabel.setForeground(Color.ORANGE);
titlelabel.setFont(new Font("Tahoma", Font.PLAIN, 25));
Panel1.add(titlelabel);
firstnum.setFont(new Font("Tahoma", Font.PLAIN, 20));
Panel1.add(firstnum);
randomOP.setFont(new Font("Tahoma", Font.PLAIN, 25));
Panel1.add(randomOP);
secondnum.setFont(new Font("Tahoma", Font.PLAIN, 20));
Panel1.add(secondnum);
equalOP.setFont(new Font("Tahoma", Font.PLAIN, 20));
Panel1.add(equalOP);
Panel1.add(answerText);
questionmark.setFont(new Font("Tahoma", Font.PLAIN, 20));
Panel1.add(questionmark);
Panel1.add(commentlabel);
JPanel Panel3 = new JPanel();
FlowLayout flowLayout3 = (FlowLayout) Panel3.getLayout();
flowLayout3.setHgap(15);
getContentPane().setLayout( new FlowLayout( FlowLayout.LEFT, 5, 5));
getContentPane().add(Panel3);
Panel3.add(excerciseButton);
Panel3.add(answerButton);
JPanel panel2 = new JPanel();
panel2.setBorder(new TitledBorder("Statistic"));
getContentPane().add(panel2);
panel2.setLayout(new GridLayout(0, 2, 0, 0));
panel2.add(correctlabel);
panel2.add(wronglabel);
correct.setForeground(Color.GREEN);
correct.setFont(new Font("Tahoma", Font.PLAIN, 25));
panel2.add(correct);
wrong.setForeground(Color.RED);
wrong.setFont(new Font("Tahoma", Font.PLAIN, 25));
panel2.add(wrong);
answerButton.addActionListener( this );
}
public static void main(String[] args) {
PracticeMath frame = new PracticeMath();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setTitle( "Math Practice");
frame.setVisible(true);
}
public void actionPerformed( ActionEvent ae )
{
String answer = answerText.getText();
int answerint = Integer.parseInt(answer);
if(one + two == answerint){
correctcounter++;
System.out.println("correct");
firstnum.setText("" + generator.nextInt(11));
randomOP.setText("" + ops[generator.nextInt(4)]);
secondnum.setText("" + generator.nextInt(11));
}
else if(one-two == answerint){
correctcounter++;
System.out.println("correct");
firstnum.setText("" + generator.nextInt(11));
randomOP.setText("" + ops[generator.nextInt(4)]);
secondnum.setText("" + generator.nextInt(11));
}
else if(one * two ==answerint){
correctcounter++;
System.out.println("correct");
firstnum.setText("" + generator.nextInt(11));
randomOP.setText("" + ops[generator.nextInt(4)]);
secondnum.setText("" + generator.nextInt(11));
}else if(one/two == answerint){
correctcounter++;
System.out.println("correct");
firstnum.setText("" + generator.nextInt(11));
randomOP.setText("" + ops[generator.nextInt(4)]);
secondnum.setText("" + generator.nextInt(11));
}
else{
wrongcounter++;
System.out.println("wrong");
firstnum.setText("" + generator.nextInt(11));
randomOP.setText("" + ops[generator.nextInt(4)]);
secondnum.setText("" + generator.nextInt(11));
}
}
}
You never reassign the variables one and two, so they are still using the same values they started with...
Try re-structuring your actionPerformed method to reduce the code duplication and assign the new equation values to the one and two variables....
public void actionPerformed(ActionEvent ae) {
String answer = answerText.getText();
int answerint = Integer.parseInt(answer);
if (one + two == answerint) {
correctcounter++;
System.out.println("correct");
} else if (one - two == answerint) {
correctcounter++;
System.out.println("correct");
} else if (one * two == answerint) {
correctcounter++;
System.out.println("correct");
} else if (one / two == answerint) {
correctcounter++;
System.out.println("correct");
} else {
wrongcounter++;
System.out.println("wrong");
}
one = generator.nextInt(11);
two = generator.nextInt(11);
firstnum.setText("" + one);
randomOP.setText("" + ops[generator.nextInt(4)]);
secondnum.setText("" + two);
}
Updated
While you are maintaining a counter of the right and wrong answers, you are not displaying them any where (freaked me out the first time I run the program).
At the bottom of the actionPerformed method, you need to update the labels displaying the number of right and wrong answers.
public void actionPerformed(ActionEvent ae) {
// ... Previous content... //
correct.setText(Integer.toString(correctcounter));
wrong.setText(Integer.toString(wrongcounter));
}
In actionPerformed, it appears you're updating the text fields (firstnum and secondnum) with new random values after each question is answered, but you're checking the answer using the variables one and two. As one and two aren't updated with the random values being displayed, they become out of sync with what is displayed after you've answered the first question.

Categories

Resources