1

I'm new to Java and have set myself the task of trying to create a simple calculator (and GUI) to advance my understanding and skills of the language.

Take this code:

import java.awt.FlowLayout;
import java.io.*;
import java.awt.*;
import java.awt.event.*; 

import javax.swing.*;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class calc extends JFrame {


    public JTextField input;
    public JTextField output;
    public JPanel Window;
    public JButton math_button[] = new JButton[5];
    public JButton number_button[] = new JButton[10];
    public String[] number_button_name = {"1","2","3","4","5","6","7","8","9","0"};
    public String[] name = {"Add", "Mulitply", "Divide", "Subtract", "Equals"};
    public JFrame frame = new JFrame(); 
    public JPanel math_panel = new JPanel();
    public JPanel number_panel = new JPanel();
    public JTextField math_input = new JTextField();
    boolean trrgger = false;

    thehandler handler = new thehandler();

    public void go()
    {

        for(int b=0; b<number_button.length; b++)
        {
            number_button[b] = new JButton(number_button_name[b]);
            number_button[b].addActionListener(handler);
            number_panel.add(number_button[b]);

        }

        for(int i=0; i<math_button.length;i++)
        {
            math_button[i] = new JButton(name[i]);
            math_button[i].addActionListener(handler);
            math_panel.add(math_button[i]);

        }


        frame.getContentPane().add(BorderLayout.NORTH, math_input);
        frame.getContentPane().add(BorderLayout.SOUTH, math_panel);
        frame.getContentPane().add(BorderLayout.CENTER, number_panel);
        frame.setSize(400,400);
        frame.setVisible(true);



    }

    //Method to handle the math and return the results of whichever 'button' was pressed
    static int Math(String button_num, int first_num, int second_num)
    {
        int total = 0;
        if(button_num == "Add")
        {
            total = first_num + second_num;
        }

        else if (button_num == "Mulitply") //multiply
        {
            total = first_num * second_num;
        }

        else if (button_num == "Divide") //divide
        {
            total = first_num / second_num;
        }

        else if (button_num == "Substract") //subtract
        {
            total = first_num - second_num;
        }

        else if (button_num == "Equals") //subtract
        {
            total = total;
        }

        return total;
    }

    //Action Events - Code that is triggered once the associated button is clicked


    public class thehandler implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {


            for (int h = 0; h <math_button.length; h++)
            {
                if(event.getSource()==math_button[h])
                {
                    int firstn = Integer.parseInt(math_input.getText());
                    math_input.setText("");
                    int secondn = Integer.parseInt(math_input.getText());

                    System.out.println(calc.Math(math_button[h].getText(), firstn, secondn));

                }

            }

            for(int n=0; n<number_button.length; n++)
            {
                if(event.getSource()==number_button[n])
                {
                    String number_clicked = (number_button[n].getText());
                    String number = math_input.getText();
                    math_input.setText(number + number_clicked);

                }



            }

        }       
    }

}

The idea behind this code is to create a simple GUI and allows the user to input the desired amount of numbers and then press the 'equals' button to display the result. However, as stated I'm having a problem with the logic. I can get the first entered number from the JTextField, clear the text once the first variable has been initialized but this is where the program falls over. The variable 'second_num' is passed to the 'Math' method as blank (which throws up errors) because that's what I tell the ActionEvent to do in order to allow for more fluid use of the program, no user wants to have to keep clearing the input box when using a calculator.

Anybody got any ideas?

Thanks

mKorbel
  • 109,525
  • 20
  • 134
  • 319
obious
  • 609
  • 8
  • 21
  • 33

2 Answers2

2
int firstn = Integer.parseInt(math_input.getText());
math_input.setText("");
int secondn = Integer.parseInt(math_input.getText());

What exactly do you expect the above lines to do? You are getting the text from math_input. Then you set it to an empty string. And by immediately getting the string back you are expecting to get something other than empty string?

The correct approach would be:

  • First time the handler is called (i.e. a "math" button is clicked) collect the input. Store it somewhere.
  • Next time this handler will be called you will have your next input. And so on until the user clicks on "=" to evaluate the whole expression.

Advice: If you are new to java, you might find it easier to create a calculator on the command line first. The functionality of a calculator does not require a GUI. In command line collecting the input is more simple. If you get that working then you can proceed to more fancy stuff like Swing

c.s.
  • 4,786
  • 18
  • 32
0

I looked at your code but its sound complicated for me. I recommend you to use IDE like Netbeans. Create swing application. To add two number all you need to do is as follow

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        int input_1 = Integer.parseInt(jTextField1.getText());
        int input_2 = Integer.parseInt(jTextField2.getText());        
        jTextField3.setText(String.valueOf((input_1+input_2)));
}

https://i.stack.imgur.com/1G4v7.jpg

Vicky Thakor
  • 3,847
  • 7
  • 42
  • 67