0

I have some problems with the creation of a simple calculator, but when asking a question (like 2-1) the system returns 0.0 as the result. I am thinking that I am not using a good way to analise information. This is how I try to set the double 't' to the number inside the textbox.

insert = new JTextField();
insert.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        try {
            i = insert.getText();
            t = Double.parseDouble(i);
        } finally {}
    }; {}
});
insert.setBackground(new Color(135, 206, 235));
insert.setText("0");
insert.setFont(new Font("Tahoma", Font.PLAIN, 18));
insert.setColumns(10);
insert.setBounds(0, 50, 292, 28);
frame.getContentPane().add(insert);

If the mistake is not there, this is the full code:

import java.awt.EventQueue;

import javax.swing.JFrame;
import java.awt.Color;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JTabbedPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.InputMethodListener;
import java.util.Scanner;
import java.awt.event.InputMethodEvent;

public class Window {
    double t, x, a, l, s;
    String w, i;
    Scanner dati = new Scanner(System. in );
    private JFrame frame;
    private JTextField result;
    private JTextField insert;
    private JTextField hint;
    private JTextField score;
    private final JButton help = new JButton("?");
    private final JButton calculator = new JButton("=");

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Window window = new Window();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Window() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.getContentPane().setBackground(new Color(135, 206, 235));
        frame.getContentPane().setLayout(null);
        calculator.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (l < 6 && l > 0) {
                    if (l != 2 && l != 3 && l != 4 && l != 5); {
                        s = x + t;
                    }
                    if (l != 1 && l != 3 && l != 4 && l != 5); {
                        s = x - t;
                    }
                    if (l != 1 && l != 2 && l != 4 && l != 5); {
                        s = x * t;
                    }
                    if (l != 1 && l != 2 && l != 3 && l != 5); {
                        s = x / t;
                    }
                    if (l != 1 && l != 2 && l != 4 && l != 3); {
                        s = (x / 100) * t;
                    }
                    result.setText(Double.toString(s));
                } else {
                    result.setText("Kļūda programmā :(");
                }
                t = 0;
                x = 0;
                l = 0;
                a = 0;
            }
        });
        calculator.setBounds(292, 57, 52, 20);
        frame.getContentPane().add(calculator);
        calculator.setBackground(new Color(135, 206, 235));
        help.setBackground(new Color(135, 206, 235));
        help.setBounds(292, 0, 52, 20);
        frame.getContentPane().add(help);

        score = new JTextField();
        score.setEditable(false);
        score.setText("\u0160eit rezult\u0101ts");
        score.setColumns(10);
        score.setBounds(344, 0, 100, 20);
        frame.getContentPane().add(score);

        hint = new JTextField();
        hint.setEditable(false);
        hint.setText("\u0160eit tavi skait\u013Ci");
        hint.setBounds(344, 57, 100, 20);
        frame.getContentPane().add(hint);
        hint.setColumns(10);

        insert = new JTextField();
        insert.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    i = insert.getText();
                    t = Double.parseDouble(i);
                } finally {}
            }; {}
        });
        insert.setBackground(new Color(135, 206, 235));
        insert.setText("0");
        insert.setFont(new Font("Tahoma", Font.PLAIN, 18));
        insert.setColumns(10);
        insert.setBounds(0, 50, 292, 28);
        frame.getContentPane().add(insert);

        result = new JTextField();
        result.setEditable(false);
        result.setBackground(new Color(135, 206, 235));
        result.setBounds(0, 0, 292, 28);
        result.setText("Hei!");
        result.setFont(new Font("Tahoma", Font.PLAIN, 18));
        frame.getContentPane().add(result);
        result.setColumns(10);

        JButton add = new JButton("+");
        add.setBackground(new Color(135, 206, 250));
        add.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                if (a != 0) {
                    x = x + t;
                    t = 0;
                    l = 1;
                } else {
                    x = t;
                    t = 0;
                    a = 1;
                    l = 1;
                }
            }
        });
        add.setBounds(0, 28, 89, 23);
        frame.getContentPane().add(add);

        JButton subtract = new JButton("-");
        subtract.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (a != 0) {
                    x = x - t;
                    t = 0;
                    l = 2;
                } else {
                    x = t;
                    t = 0;
                    a = 1;
                    l = 2;
                }
            }
        });
        subtract.setBackground(new Color(135, 206, 235));
        subtract.setBounds(89, 28, 89, 23);
        frame.getContentPane().add(subtract);

        JButton multiply = new JButton("x");
        multiply.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (a != 0) {
                    x = x * t;
                    t = 0;
                    l = 3;
                } else {
                    x = t;
                    t = 0;
                    a = 1;
                    l = 3;
                }
            }
        });
        multiply.setBackground(new Color(135, 206, 235));
        multiply.setForeground(new Color(0, 0, 0));
        multiply.setBounds(178, 28, 89, 23);
        frame.getContentPane().add(multiply);

        JButton divide = new JButton("/");
        divide.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (a != 0) {
                    x = x / t;
                    t = 0;
                    l = 4;
                } else {
                    x = t;
                    t = 0;
                    a = 1;
                    l = 4;
                }
            }
        });
        divide.setBackground(new Color(135, 206, 235));
        divide.setBounds(266, 28, 89, 23);
        frame.getContentPane().add(divide);

        JButton percent = new JButton("%");
        percent.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (a != 0) {
                    x = (x / 100) * t;
                    t = 0;
                    l = 5;
                } else {
                    x = t;
                    t = 0;
                    a = 1;
                    l = 5;
                }
            }
        });
        percent.setBackground(new Color(135, 206, 235));
        percent.setBounds(355, 28, 89, 23);
        frame.getContentPane().add(percent);
        frame.setBounds(100, 100, 460, 115);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        dati.close();
    }
}

Possibly I am using a bad way to calculate.

If you want a simple explanation, I am trying to create a calculator with five functions - +, -, *, /, % - and has one text box to insert the numbers you want to calculate - insert, click function button, insert, click function button, when done - the = button. '?' button is planned to give a description of the calculator. I am making it for a school project, by the way.

Thanks in advance.

P.S. Kļūda programmā translates to fault in program.

Frakcool
  • 10,915
  • 9
  • 50
  • 89
Artis
  • 1
  • 2
  • I'd be reluctant to discard any parsing exceptions in the way that you do. At least write the exception message to stderr. This could help identify the problem. – Bathsheba Dec 08 '15 at 19:14
  • If that was my code, i'd put a JLabel somewhere displaying all values of x,t,a,l and update in every actionPerformed – Jan Dec 08 '15 at 19:21
  • I want to notify that it is usually not a good practise to have a really huge method, split it up by implementing classes for the action listeners; it cleans the code up for a bit – engineercoding Dec 08 '15 at 19:29

1 Answers1

3

On your actionListener you have a ; before each { on the if statements. Also, your conditions are strange, change it from this. And add else statements or a switch

calculator.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if (l < 6 && l > 0) {
            if (l != 2 && l != 3 && l != 4 && l != 5); {
                s = x + t;
            }
            if (l != 1 && l != 3 && l != 4 && l != 5); {
                s = x - t;
            }
            if (l != 1 && l != 2 && l != 4 && l != 5); {
                s = x * t;
            }
            if (l != 1 && l != 2 && l != 3 && l != 5); {
                s = x / t;
            }
            if (l != 1 && l != 2 && l != 4 && l != 3); {
                s = (x / 100) * t;
            }
            result.setText(Double.toString(s));
        } else {
            result.setText("Kļūda programmā :(");
        }
        t = 0;
        x = 0;
        l = 0;
        a = 0;
    }
});

To this:

calculator.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if (l < 6 && l > 0) {
            if (l == 1) {
                s = x + t;
            } else if (l == 2) {
                s = x - t;
            } else if (l == 3) {
                s = x * t;
            } else if (l == 4) {
                s = x / t;
            } else if (l == 5) {
                s = (x / 100) * t;
            }
            result.setText(Double.toString(s));
        } else {
            result.setText("Kļūda programmā :(");
        }
        t = 0;
        x = 0;
        l = 0;
        a = 0;
    }
});

Or this one (Recommended):

calculator.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        switch (l) {
            case 1:
                s = x + t;
                result.setText(Double.toString(s));
                break;
            case 2:
                s = x - t;
                result.setText(Double.toString(s));
                break;
            case 3:
                s = x * t;
                result.setText(Double.toString(s));
                break;
            case 4:
                s = x / t;
                result.setText(Double.toString(s));
                break;
            case 5:
                s = (x / 100) * t;
                result.setText(Double.toString(s));
                break;
            default:
                result.setText("Kļūda programmā :(");
                break;
        }
        t = 0;
        x = 0;
        l = 0;
        a = 0;
    }
});

And as an aside recommendation avoid using Null Layout, instead use a Layout Manager or combinations of them. This will prevent bugs since Swing was designed to work with them. For more information about this read Why is it frowned upon to use a null layout in swing. Also please check The use of multiple JFrames, Good / Bad Practice


Edit

To get a very similar view from your program and get it to work, you could try something like this, which doesn't use a null layout and prints the value each time you clic the + button. All the rest of buttons don't work yet (See how my code works with these buttons and take this logic to the rest of them):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class LayoutExample {
    double number = 0;
    JFrame frame;
    JLabel label;
    JTextField field;
    JButton add, substract, mult, divide, total, help, perc;
    JPanel topPane, buttonPane, fieldPane;
    LayoutExample() {
        frame = new JFrame("Calculator");
        label = new JLabel("Result: ");
        field = new JTextField("0");
        add = new JButton("+");
        substract = new JButton("-");
        mult = new JButton("*");
        divide = new JButton("/");
        total = new JButton("=");
        perc = new JButton("%");
        help = new JButton("?");
        topPane = new JPanel();
        buttonPane = new JPanel();
        fieldPane = new JPanel();
        
        field.setColumns(10);
        
        topPane.setLayout(new FlowLayout());
        buttonPane.setLayout(new FlowLayout());
        fieldPane.setLayout(new FlowLayout());
        
        topPane.add(label);
        topPane.add(help);
        
        add.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    number += Integer.parseInt(field.getText());
                } catch (NumberFormatException nfe) {
                    nfe.printStackTrace();
                }
            }
        });
        
        total.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                label.setText("Result: " + number);
            }
        });
        
        buttonPane.add(add);
        buttonPane.add(substract);
        buttonPane.add(mult);
        buttonPane.add(divide);
        buttonPane.add(perc);
        
        fieldPane.add(field);
        fieldPane.add(total);
        
        frame.add(topPane, BorderLayout.PAGE_START);
        frame.add(buttonPane, BorderLayout.CENTER);
        frame.add(fieldPane, BorderLayout.PAGE_END);
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String args[]) {
        new LayoutExample();
    }
}

The output is very similar to the one you did as you can see:

enter image description here

Community
  • 1
  • 1
Frakcool
  • 10,915
  • 9
  • 50
  • 89
  • Hello. Whilst this is something useful, my problem is still not fixed. Currently I am seeing that the double 't' is 0.0 the whole time, and is not changing... is there any way I can fix that? By the way, I am a massive Java rookie - I've been coding in Java, or in a wider scale - outside of Scratch - for around 3 days... so help would be appreciated. – Artis Dec 09 '15 at 17:08
  • @Artis please post a [Runnable Example](http://stackoverflow.com/help/mcve) your code is A LOT and I don't have enough time to check it all. Make a simple copy of this one with the minimum code so I can check the issue there, it'll be easier to find then. I don't know what you mean or where you're seeing a double 't' ? – Frakcool Dec 09 '15 at 17:18
  • I've checked it and I'm afraid to tell you, that you **must** redo the whole program, as is, it will be harder and take more time for me / you / anyone who wants to help you with this to fix it. Better create a new one from scratch and avoid using null layout. Once you have it, please post another question with the minimum code to test it – Frakcool Dec 09 '15 at 17:46