I am writing a Mortgage Calculator for class and I have it working the way I need it to, except everytime I click the "Calculate" button it will just continue to add to the table instead of the table clearing and showing new values. I know my code might look a little sloppy and I have some things commented out that don't need to be there because I'm still working it, but do you have any suggestions?
FYI I am still a beginner learning Java and it has taken me over 20hrs to get this far (and i"m pretty proud of myself!) Thank you!!
//Import all required Packages
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.text.*;
import java.awt.event.*;
public class MortgageCalculator extends JFrame implements ActionListener {
// Loan Values
double intPrincipal, interestRate, calcPayment, monthlyInterest, currentInterest, principalPaid, newBalance;
int totalMonths;
double[] loanInterest = {5.35, 5.5, 5.75}; // Yearly interest in decimal form
int[] loanTerm = {7, 15, 30}; // Total months of term
String principal;
String comboArray[] = {"7 Years at 5.35%", "15 Years at 5.5%", "30 Years at 5.75%"};
int termYears, termMonths, done, i=0, m=0, p=0;
//Set up panels
JPanel contentPanel;
//Set up labels
JLabel mortgageLabel, paymentLabel, termLabel;
//Set up buttons
JButton calculateButton, clearButton, exitButton;
//TextFields
JTextField txtMortgage = new JTextField(10);
JTextField txtPayment = new JTextField(10);
//New Text Area
JTextArea textarea = new JTextArea();
DecimalFormat df = new DecimalFormat("$###,###.00"); //Formatting the results to decimal form
//Combo Box
JComboBox loansList = new JComboBox();
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
//Build GUI
public MortgageCalculator()
{
super();
initializeContent();
}
public void initializeContent()
{
this.setSize(700, 500);
this.setLocation(0, 0);
this.setContentPane(contentPanel());
this.setTitle("Mortgage Calculator");
}
public JPanel contentPanel()
{
contentPanel = new JPanel();
contentPanel.setLayout(null);
//Add labels to the panel
mortgageLabel = new JLabel("Mortgage:");
mortgageLabel.setLocation(200, 30);
mortgageLabel.setSize(100, 25);
contentPanel.add(mortgageLabel);
termLabel = new JLabel("Term & Rate:");
termLabel.setLocation(183, 55);
termLabel.setSize(100, 30);
contentPanel.add(termLabel);
paymentLabel = new JLabel("Monthly Payment:");
paymentLabel.setLocation(158, 85);
paymentLabel.setSize(100, 30);
contentPanel.add(paymentLabel);
//Text Fields
txtMortgage = new JTextField(10);
txtMortgage.setLocation(280, 30);
txtMortgage.setSize(150, 25);
contentPanel.add(txtMortgage);
txtPayment = new JTextField(10);
txtPayment.setLocation(280, 85);
txtPayment.setSize(150, 25);
contentPanel.add(txtPayment);
//Combo Box
loansList.addItem(comboArray[0]);
loansList.addItem(comboArray[1]);
loansList.addItem(comboArray[2]);
loansList.setLocation(280, 55);
loansList.setSize(150, 25);
loansList.addActionListener(this);
contentPanel.add(loansList);
//textarea.setPreferredSize(new Dimension(650, 300));
//JScrollPane scroller = new JScrollPane(textarea);
JScrollPane scroller = new JScrollPane(table);
contentPanel.add(scroller);
scroller.setSize(650,300);
scroller.setLocation(20, 150);
textarea.setLineWrap(true);
model.addColumn("Payment Number");
model.addColumn("Current Interest");
model.addColumn("Principal Paid");
model.addColumn("New Balance");
//Buttons
exitButton = new JButton("Exit");
exitButton.setLocation(450, 30);
exitButton.setSize(100, 25);
contentPanel.add(exitButton);
clearButton = new JButton("Clear");
clearButton.setLocation(450, 55);
clearButton.setSize(100, 25);
contentPanel.add(clearButton);
calculateButton = new JButton("Calculate");
calculateButton.setLocation(450, 85);
calculateButton.setSize(100, 25);
contentPanel.add(calculateButton);
//setup up buttons
calculateButton.addActionListener(this);
clearButton.addActionListener(this);
exitButton.addActionListener(this);
return contentPanel;
}
//Define actions performed for buttons
public void actionPerformed(ActionEvent e)
{
String arg = e.getActionCommand();
if (e.getSource() == loansList) {
switch (loansList.getSelectedIndex()) {
case 0:
i = 0;
break;
case 1:
i = 1;
break;
case 2:
i = 2;
break;
}
}
if (arg == "Calculate")
{
txtPayment.setText("");
principal = txtMortgage.getText();
try {
intPrincipal = Double.parseDouble(principal);
if (intPrincipal <= 0) throw new NumberFormatException();
}
catch(NumberFormatException n){
txtPayment.setText("Please Enter a Postive Numeric Number");
done = 1;
}
if (done == 1)
done = 0;
else {
interestRate = loanInterest[i];
termYears = loanTerm[i];
monthlyInterest = interestRate/(12*100); //calculates monthly interest
termMonths = termYears*12; //calculates term length in months
calcPayment = monthlyInterest*intPrincipal/(1-Math.pow((1+monthlyInterest), -termMonths)); //calculates monthly payment
txtPayment.setText(" " + df.format(calcPayment));
for (m=0; m<=totalMonths; m++) {
totalMonths = loanTerm[i]*12;
currentInterest = intPrincipal * monthlyInterest;
principalPaid = calcPayment - currentInterest;
newBalance = intPrincipal - principalPaid;
intPrincipal = newBalance;
/* printAndAppend(
(m+1) + " " +
df.format(currentInterest) + " " +
df.format(principalPaid) + " " +
df.format(newBalance) + "\n");
//textarea.setText(df.format(currentInterest));
if(intPrincipal <= 1){ break;}*/
// Create a couple of columns
model.addRow(new Object[]{m+1, df.format(currentInterest), df.format(principalPaid), df.format(newBalance)});
if(intPrincipal <= 1){ break;}
}
}
}
else if (e.getSource() == clearButton)
{
txtMortgage.setText(""); //clear Mortgage textfield
txtPayment.setText(""); //clear Payment textfield
txtMortgage.requestFocusInWindow(); //move cursor back to Mortgage textfield
loansList.setSelectedIndex(0);
}
else if (e.getSource() == exitButton)
System.exit(0);
}
public void printAndAppend(String text) {
textarea.append(text);
}
public static void main(String[] args)
{
new MortgageCalculator().setVisible(true);
}
}
To clear all you need to do is set the row count of the model to 0 -- that's it:
else if (e.getSource() == clearButton) {
txtMortgage.setText("");
txtPayment.setText("");
txtMortgage.requestFocusInWindow();
loansList.setSelectedIndex(0);
model.setRowCount(0); //!! added
}
Also, this is not good:
if (arg == "Calculate") {
As you shouldn't use == to compare Strings. If you want to compare Strings, use the equals method:
if (arg.equals("Calculate")) {
or the equalsIgnoreCase method:
if (arg.equalsIgnoreCase("Calculate")) {
The reason this is important is because == checks to see if one String object is the same as another String object, and you really don't care about this. Instead you want to know if one String holds the same chars as another, and that's what equals tests for.
Also, I'd set the model's row count to 0 at the beginning of your calculate method, and this way you can recalculate things without having to clear.
Related
I am trying to code a simple calculator like the one you would see in windows (non-scientific). I can not for the life of me figure out how to properly change the text after pressing an operator but still see the original entry that wont change until the next digit is pressed, have the equals key do the same operation if used multiple times (ie: 5+5 = 10 +5 = 15), and when I input a digit that is the same (5+5) it won't accept the second digit. I know I am very close and am probably missing a certain boolean that could allow my code to work properly, but Im not sure where to look. Thanks for any help.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JCalculator extends JFrame implements ActionListener {
/** intialize the jlabel, jbutton, string that makes the buttons and jpanel that will hold the buttons
*
*/
private JTextField display = new JTextField("0", SwingConstants.RIGHT);
private JPanel buttonPanel = new JPanel();
private JPanel displayPanel = new JPanel();
private JButton newButton, divButton, multiButton, equalsButton, clearButton, plusButton, minusButton;
private String[] arrayButtons = {"7","8", "9", "/", "4", "5", "6", "x", "1", "2", "3", "-", "0","C", "=", "+"};
private int operand = 0;
private int firstInput = 0, secondInput = 0, answer = 0;
JCalculator() {
/** creates the jframe */
JFrame jfrm = new JFrame("Calculator");
/** sets the size of the jfrm and then positions it in the center of screen */
jfrm.setSize(480, 300);
jfrm.setLocationRelativeTo(null);
/** sets the program to close on exit */
jfrm.setDefaultCloseOperation(jfrm.EXIT_ON_CLOSE);
/** ImageIcon img = new ImageIcon(JCalculator.png);
*
*/
/**sets initial layout to border */
jfrm.setLayout(new BorderLayout());
/** makes a panel named display that holds the Jtext display
* enables it and justifies it right
*/
displayPanel.setLayout(new BorderLayout());
displayPanel.add(display, BorderLayout.CENTER);
display.setHorizontalAlignment(JTextField.RIGHT);
display.setEnabled(false);
/** makes a panel for buttons that is a grid layout
*
*/
buttonPanel.setLayout(new GridLayout(4,4));
/** makes a loop to make all of the 16 buttons for the calculator
* the operands all have their own specific buttons
*/
for (int i = 0; i < arrayButtons.length; i++) {
if (arrayButtons[i].equals("/")) {
divButton = new JButton(arrayButtons[i]);
divButton.addActionListener(this);
buttonPanel.add(divButton);
} else if (arrayButtons[i].equals("x")) {
multiButton = new JButton(arrayButtons[i]);
multiButton.addActionListener(this);
buttonPanel.add(multiButton);
} else if (arrayButtons[i].equals("=")) {
equalsButton = new JButton(arrayButtons[i]);
equalsButton.addActionListener(this);
buttonPanel.add(equalsButton);
} else if (arrayButtons[i].equals("C")) {
clearButton = new JButton(arrayButtons[i]);
clearButton.addActionListener(this);
buttonPanel.add(clearButton);
} else if (arrayButtons[i].equals("+")) {
plusButton = new JButton(arrayButtons[i]);
plusButton.addActionListener(this);
buttonPanel.add(plusButton);
} else if (arrayButtons[i].equals("-")) {
minusButton = new JButton(arrayButtons[i]);
minusButton.addActionListener(this);
buttonPanel.add(minusButton);
} else {
newButton = new JButton(arrayButtons[i]);
newButton.addActionListener(this);
buttonPanel.add(newButton);
}
}
/** adds the two panels to the jfrm
* sets jfrm visibility to true
* sets equalsButton to the default button
*/
jfrm.add(displayPanel, BorderLayout.NORTH);
jfrm.add(buttonPanel, BorderLayout.CENTER);
jfrm.getRootPane().setDefaultButton(equalsButton);
jfrm.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String s = ae.getActionCommand();
char stringCheck = s.charAt(0);
if (answer == Integer.parseInt(display.getText())) {
display.setText("0");
}
if (Character.isDigit(stringCheck) && display.getText().length() < 8) {
if (display.getText().equals("0")) {
display.setText(s);
} else {
display.setText(display.getText().concat(s));
}
} if (s.equals("+")){
answer = Integer.parseInt(display.getText());
operand = 1;
} if (s.equals( "-")){
answer = Integer.parseInt(display.getText());
operand = 2;
} if (s.equals("x")){
answer = Integer.parseInt(display.getText());
operand = 3;
} if (s.equals("/")){
answer = Integer.parseInt(display.getText());
operand = 4;
} if (s.equals("C")){
firstInput = 0;
secondInput = 0;
answer = 0;
operand = 0;
display.setText("0");
} if (s.equals("=")){
switch(operand){
case 1:
answer += Integer.parseInt(display.getText());
display.setText(Integer.toString(answer));
break;
case 2:
answer -= Integer.parseInt(display.getText());
display.setText(Integer.toString(answer));
break;
case 3:
answer *= Integer.parseInt(display.getText());
display.setText(Integer.toString(answer));
break;
case 4:
if(Integer.parseInt(display.getText()) > 0 || Integer.parseInt(display.getText()) < 0) {
answer /= Integer.parseInt(display.getText());
display.setText(Integer.toString(answer));
break;
} else {
display.setText("Div by 0");
}
}
if(answer > 100000000 || answer < -100000000){
display.setText("Overlow");
}
}
}
public static void main (String [] args){
/**
* run program
*/
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JCalculator();
}
});
}
}
I have been creating a calculator as a beginner in Java. I have added in buttons that have a more complex functionality, and for some reason they just don't work.
Can somebody please educate me on why these java calculations are not working properly?
The buttons that work fine are the plus, minus, multiply and divide.
The buttons that aren't working so well are the percentage, squareRt, and the PlusMinus buttons.
You can see in the calculator engine that I have implemented the correct method of calculation, however when the problematic buttons are pressed, the text display area of the calculator goes blank, when for example, if you press in 64 on the calculator and then press sqrt, it is suppose to display the Square root of 64, but is not doing so. Thanks for any help in advance. (take it easy on me i'm a beginner)
Here is the calculator
package Calculator;
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
public class Calculator {
// Declare and instantiate window components
JButton button0 = new JButton("0");
JButton button1 = new JButton("1");
JButton button2 = new JButton("2");
JButton button3 = new JButton("3");
JButton button4 = new JButton("4");
JButton button5 = new JButton("5");
JButton button6 = new JButton("6");
JButton button7 = new JButton("7");
JButton button8 = new JButton("8");
JButton button9 = new JButton("9");
JButton buttonPoint = new JButton(".");
JButton buttonEqual = new JButton("=");
JButton buttonPlus = new JButton("+");
JButton buttonMinus = new JButton("-");
JButton buttonDivide = new JButton("/");
JButton buttonMultiply = new JButton("*");
JButton buttonSquareRt = new JButton("sqrt");
JButton buttonPercentage = new JButton("%");
JButton buttonPlusMinus = new JButton("+/-");
JButton buttonClear = new JButton("C");
JPanel windowContent = new JPanel();
JTextField displayField = new JTextField(30);
// Constructor
Calculator() {
// Set the layout manager for this panel
BorderLayout bl = new BorderLayout();
windowContent.setLayout(bl);
// Add the display field to the top of the window
windowContent.add("North", displayField);
// Create the panel with the GridLayout
// that will contain 12 buttons - 10 numeric ones, and
// buttons with the point and the equal sign
JPanel p1 = new JPanel();
GridLayout gl = new GridLayout(4, 3);
p1.setLayout(gl);
p1.add(button1);
p1.add(button2);
p1.add(button3);
p1.add(button4);
p1.add(button5);
p1.add(button6);
p1.add(button7);
p1.add(button8);
p1.add(button9);
p1.add(button0);
p1.add(buttonPoint);
p1.add(buttonEqual);
// Add the panel p1 to the centre area of the window
windowContent.add("Center", p1);
// Create the panel with the GridLayout
// that will contain 4 action buttons -
// Plus, Minus, Divide and Multiply
JPanel p2 = new JPanel();
GridLayout gl2 = new GridLayout(4, 1);
p2.setLayout(gl);
p2.add(buttonPlus);
p2.add(buttonMinus);
p2.add(buttonMultiply);
p2.add(buttonDivide);
//adding the task buttons to go on extra column
p2.add(buttonSquareRt);
p2.add(buttonPercentage);
p2.add(buttonPlusMinus);
p2.add(buttonClear);
// Add the panel p2 to the east area of the window
windowContent.add("East", p2);
// Create the frame and add the content pane to it
JFrame frame = new JFrame("Calculator");
frame.setContentPane(windowContent);
// set the size of the window to be big enough to
// accommodate all window controls
frame.pack();
// Display the window
frame.setVisible(true);
// Instantiate the event listener and
// register each button with it
CalculatorEngine calcEngine = new CalculatorEngine(this);
button0.addActionListener(calcEngine);
button1.addActionListener(calcEngine);
button2.addActionListener(calcEngine);
button3.addActionListener(calcEngine);
button4.addActionListener(calcEngine);
button5.addActionListener(calcEngine);
button6.addActionListener(calcEngine);
button7.addActionListener(calcEngine);
button8.addActionListener(calcEngine);
button9.addActionListener(calcEngine);
buttonPoint.addActionListener(calcEngine);
buttonPlus.addActionListener(calcEngine);
buttonMinus.addActionListener(calcEngine);
buttonDivide.addActionListener(calcEngine);
buttonMultiply.addActionListener(calcEngine);
buttonEqual.addActionListener(calcEngine);
buttonSquareRt.addActionListener(calcEngine);
buttonPercentage.addActionListener(calcEngine);
buttonPlusMinus.addActionListener(calcEngine);
buttonClear.addActionListener(calcEngine);
}
public static void main(String[] args) {
// Instantiate the class Calculator
Calculator calc = new Calculator();
}
}
And here is the engine with the problematic code
package Calculator;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
public class CalculatorEngine implements ActionListener {
Calculator parent; // a reference to Calculator window
char selectedAction = ' '; // +, -, /, or *
double currentResult = 0;
// Constructor stores the reference to the Calculator
// window in the member variable parent
CalculatorEngine(Calculator parent) {
this.parent = parent;
}
public void actionPerformed(ActionEvent e) {
// Get the source of this action
JButton clickedButton = (JButton) e.getSource();
String dispFieldText = parent.displayField.getText();
double displayValue = 0;
// Get the number from the text field
// if it’s not empty
if (!"".equals(dispFieldText)) {
displayValue = Double.parseDouble(dispFieldText);
}
Object src = e.getSource();
// For each action button memorize selected
// action +, -, /, or *, store the current value
// in the currentResult, and clean up the display
// field for entering the next number
if (src == parent.buttonPlus) {
selectedAction = '+';
currentResult = displayValue;
parent.displayField.setText("");
} else if (src == parent.buttonMinus) {
selectedAction = '-';
currentResult = displayValue;
parent.displayField.setText("");
} else if (src == parent.buttonDivide) {
selectedAction = '/';
currentResult = displayValue;
parent.displayField.setText("");
} else if (src == parent.buttonMultiply) {
selectedAction = '*';
currentResult = displayValue;
parent.displayField.setText("");
} else if (src == parent.buttonSquareRt) {
selectedAction = 's';
currentResult = displayValue;
parent.displayField.setText("");
} else if (src == parent.buttonPercentage){
selectedAction = 'p';
currentResult = displayValue;
parent.displayField.setText("");
} else if (src == parent.buttonPlusMinus){
selectedAction = 'm';
currentResult = displayValue;
parent.displayField.setText("");
}
else if (src == parent.buttonEqual) {
// Perform the calculations based on selectedAction
// update the value of the variable currentResult
// and display the result
if (selectedAction == '+') {
currentResult += displayValue;
// Convert the result to String by concatenating
// to an empty string and display it
parent.displayField.setText("" + currentResult);
} else if (selectedAction == '-') {
currentResult -= displayValue;
parent.displayField.setText("" + currentResult);
} else if (selectedAction == '/') {
currentResult /= displayValue;
parent.displayField.setText("" + currentResult);
} else if (selectedAction == '*') {
currentResult *= displayValue;
parent.displayField.setText("" + currentResult);
} else if (selectedAction == 's') {
currentResult = Math.sqrt(displayValue);
parent.displayField.setText("" + currentResult);
} else if (selectedAction == 'p') {
currentResult = currentResult / 100;
parent.displayField.setText("" + currentResult);
} else if (selectedAction == 'm') {
displayValue = currentResult * -1;
parent.displayField.setText("" + currentResult);
}
} else {
// For all numeric buttons append the button's
// label to the text field
String clickedButtonLabel = clickedButton.getText();
parent.displayField.setText(dispFieldText + clickedButtonLabel);
}
}
}
It appears that this code would work as expected where you would type a number like 64, then you would press the square root button - which would clear the displayField - then you would press the equals button, and it would display the result.
If you want to make it more obvious that you should be pressing the equals button to get the result, you might want to echo the users entry surrounded by text that represents the function to be performed, for example:
else if (src == parent.buttonSquareRt) {
selectedAction = 's';
currentResult = displayValue;
parent.displayField.setText("sqrt(" + currentResult + ")");
}
hello i was wondering how do i link my logic class to my gui class?
i have wrote a logic class which is the structure then had to give it an interface; so i wrote another class which is the gui class but idk how to make the GUI class grab the variable from the logic class.
P.S: its a number guessing game that the user has to guess a numb btw 1-10.
LOGIC CLASS
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class GG {
public static void main(String[] args)
{
//random number
Random rand = new Random();
int answer = rand.nextInt(10) +1;
int guess = 0;
int attempts = 0;
public
//user's guess
Scanner keyboard = new Scanner(System.in);
GuessingGameGui gui = new GuessingGameGui();
gui.setVisible(true);
while(answer != guess)
{
try
{
System.out.print("Guess a number between 1 and 10: ");
attempts++;
guess = keyboard.nextInt();
if (guess < 1 || guess > 10)
//throw new BadGuessException()
throw new BadGuessException("invalid entry (" + attempts + " attempts so far)");
}
catch (BadGuessException e)
{
System.out.println(e.getMessage());
}
catch (InputMismatchException e)
{
System.out.println("Please enter integers only, and try again");
keyboard.next(); //to get rid of infinite loop issue
}
}
System.out.println("YOU GOT IT (" + attempts + "attempts )");
}
}
GUI CLASS
public class GuessingGameGui extends JFrame {
public GuessingGameGui() {
final int WINDOW_WIDTH = 650; // Window width in pixels
final int WINDOW_HEIGHT = 250; // Window height in pixels
setTitle("Guessing Game");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel north = new JPanel();
JLabel lab1 = new JLabel("Guess a number between 1 and 10?");
setLayout(new FlowLayout());
north.add(lab1);
add( north );
JPanel center = new JPanel();
final JTextField titleText = new JTextField();
titleText.setPreferredSize( new Dimension( 200, 24 ) );
setLayout(new FlowLayout());
JButton button = new JButton("Guess");
Action action = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
String typed = titleText.getText();
int guess = Integer.parseInt(typed);
}
};
titleText.addActionListener( action );
button.addActionListener( action );
center.add(titleText);
center.add(button);
add( center );
JPanel south = new JPanel();
JLabel lab2 = new JLabel("YOU GOT IT " + attempts);
south.add(lab2);
add( south );
}
}
A common way is to add the Logic object to the GUI, for example through the constructor. Then whenever something is happening on the GUI you need to call the correct methods on the Logic object and update the display if needed.
I trying to make a math quiz game that generates random question and keep track of of what question are wrong and write.
I trying to figure out how to make my program respond if the answer written in the text field is correct or incorrect when I click the JButton `answerbutton`. I'm very new to using `ActionListener`.
ok so i got action listener to work but when i type in a answer it say my answeris wrong, even though it right. the first question that appear work fine but after that it , it say all my answer are wrong and it still wont keep track of my 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 {
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));
}
}
}
In order to make your buttons do some desired action, like you say, you will need to use an ActionListener. To do this, you will want to define some class that implements the ActionListener interface. This class can be your PracticeMath class, if you want it to be. So do this:
public class PracticeMath extends JFrame implements ActionListener
{...}
When you do this, your PracticeMath class will be responsible for specifying a definition to any methods that are part of the ActionListener interface; in this case
public void actionPerformed( ActionEvent ae )
{
// put something intelligent here
}
You then need to add this ActionListener to whichever buttons you want it to listen to. Namely
answerButton.addActionListener( this );
Use "this" as the argument since your ActionListener is your PracticeMath class. Now, when you press the answer button, whatever code you put into your actionPerformed(...) method will be called. So you can evaluate your answer within.
Update to reflect the comment below:
Here is what your code should look like for the actionPerformed method.
public void actionPerformed( ActionEvent ae )
{
String answer = answerText.getText();
int answerint = Integer.parseInt(answer);
if(one + two == answerint){
correctcounter++;
System.out.println("correct");
one = generator.nextInt(11);
two = generator.nextInt(11);
// I don't know if you actually store the operator anywhere
operator = ops[generator.nextInt(4)];
firstnum.setText("" + one);
randomOP.setText("" + operator);
secondnum.setText("" + two);
}
else if(one-two == answerint){
// ... and do the same for the other cases too
This, ofcourse, does not address the fact that you are not checking to see if the correct operator was actually used, but this should fix the problem with every answer past the first one being labeled as incorrect.
Ok, I'm kinda new to java. I'm making a program that solves for one step equations. I'm having some difficulties running it though. Here is the code for my main file, Main.java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
Solve solve = new Solve();
JButton add = new JButton("Add");
JButton sub = new JButton("Subtract");
JButton mult = new JButton("Multiply");
JButton div = new JButton("Divide");
JButton solv = new JButton("Solve!");
JTextArea one = new JTextArea();
JLabel two = new JLabel(" = ");
JLabel three = new JLabel("X");
JLabel four = new JLabel();
JTextArea five = new JTextArea();
JLabel solved = new JLabel();
JPanel row1 = new JPanel();
JPanel row2 = new JPanel();
JPanel row3 = new JPanel();
public double funct;
public Main() {
super("Solving a one step equation!");
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
GridLayout layout = new GridLayout();
setLayout(layout);
FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER);
row1.setLayout(layout1);
row1.add(add);
row1.add(sub);
row1.add(mult);
row1.add(div);
row1.add(solv);
add(row1);
add.addActionListener(this);
sub.addActionListener(this);
mult.addActionListener(this);
div.addActionListener(this);
solv.addActionListener(this);
GridLayout layout2 = new GridLayout(1, 1, 1, 1);
row2.setLayout(layout2);
row2.add(one, BorderLayout.CENTER);
row2.add(two, BorderLayout.CENTER);
row2.add(three, BorderLayout.CENTER);
row2.add(four, BorderLayout.CENTER);
row2.add(five);
add(row2, BorderLayout.CENTER);
GridLayout layout3 = new GridLayout(5, 5, 5, 5);
row3.setLayout(layout3);
row3.add(solved);
add(row3);
}
public static void main(String[] args) {
Main frame = new Main();
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if(source == add)
{
four.setText(" + ");
funct = 1;
}
else if(source == sub)
{
four.setText(" - ");
funct = 2;
}
else if(source == mult)
{
four.setText(" * ");
funct = 3;
}
else if(source == div)
{
four.setText(" / ");
funct = 4;
}
if(source == solv)
{
if(funct == 1)
{
double Ones = Double.parseDouble(three.getText());
double Twos = Double.parseDouble(three.getText());
solved.setText("X = " + solve.Add(Ones, Twos));
}
else if(funct == 2)
{
double Ones = Double.parseDouble(three.getText());
double Twos = Double.parseDouble(three.getText());
solved.setText("X = " + solve.Sub(Ones, Twos));
}
else if(funct == 3)
{
double Ones = Double.parseDouble(three.getText());
double Twos = Double.parseDouble(three.getText());
solved.setText("X = " + solve.Mult(Ones, Twos));
}
else if(funct == 4)
{
double Ones = Double.parseDouble(three.getText());
double Twos = Double.parseDouble(three.getText());
solved.setText("X = " + solve.Div(Ones, Twos));
}
}
}
}
Here is the code for my other file, Solve.java
public class Solve {
public double Add(double One, double Two)
{
return One - Two;
}
public double Sub(double One, double Two)
{
return One + Two;
}
public double Mult(double One, double Two)
{
return One / Two;
}
public double Div(double One, double Two)
{
return One * Two;
}
}
Some help would be appreciated. Anyone see what I'm doing wrong?
You get a NumberFormatException once 'Solve' button is clicked. It seems like a copy/paste issue - you are not retrieving the correct numbers. You are trying to convert 'X' string to double. It is best if you give meaningful names to your variables. To fix the exception, try this, replace :
double Ones = Double.parseDouble(three.getText());
double Twos = Double.parseDouble(three.getText());
with:
double Ones = Double.parseDouble(one.getText());
double Twos = Double.parseDouble(five.getText());
Get familiar with Java Code Conventions, Naming Conventions section in particular.
In addition to #Max's helpful answer, here are a few other suggestions:
Setting the frame's layout to new GridLayout() defaults to a single row and column with no padding. As an alternative, consider new GridLayout(0, 1, 5, 5), which produces any number of rows in one column with 5x5 padding. Then you can focus on the layout of each row:
row1.setLayout(new FlowLayout(FlowLayout.CENTER));
row2.setLayout(new FlowLayout(FlowLayout.CENTER));
row3.setLayout(new GridLayout(1, 1, 5, 5));
Move your setVisible() call to the end of the frame's constructor:
pack();
setLocationRelativeTo(null);
setVisible(true);
Consider getRootPane().setDefaultButton(solv) to make the Solve button the default.
Consider making addition the default:
private JLabel four = new JLabel("+");
private int funct = 1; // add by default
Consider using JTextField for number entry:
private JTextField one = new JTextField(10);
private JTextField five = new JTextField(10);