aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Please need help with calculator program... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Please need help with calculator program..." Watch "Please need help with calculator program..." New topic
Author

Please need help with calculator program...

Alex Reynders
Greenhorn

Joined: Nov 16, 2008
Posts: 13
Hi guys, I please need your help with this small project that I need to do for an assignment.
(I'm a correspondent student so I am allowed help from outside as long as I understand it when the exams come.)

I have attached a .doc file for you to see what the project specifations are as well as the output of my program (that I did so far).

There are a few things that I'm really struggling with and I would very much appreciate your help.

1. As you can see I have created a frame to hold the textfield and the buttons and I've created a menu bar as per the specifications.
I know that I have to add listeners so that the user input can be used to calculate whatever he/she inserted, I was thinking about
a 'MouseListener' because the user is going to use the mouse to click on the buttons etc. (not necessary for keyboard input).

But now my problem is this:
I'm not sure how to code the listener so that if the user e.g. clicks on '3' it shows in the text field then clicks on an operator and after that on e.g. '2' which is also shown
in the textfield, then when the user clicks on '=' the answer must be shown???

Here is my code for this program so far:



P.S - sorry for the long post but I had to explain my situation in full.

Please help me, I really need your help.
Thanks in advance.



Omar Al Kababji
Ranch Hand

Joined: Jan 13, 2009
Posts: 357
Hi i am not going to give you a complete code however here are some points you will need:

you will have two variables two hold the operands and a variable to hold the operations type (addition, subtraction ...etc).

to add a listener to the buttons you have to do the following:

supposing you have a button named "button1" write the following code :



have fun with the logic you will need ;)


(peace)


Omar Al Kababji - Electrical & Computer Engineer
[SCJP - 90% - Story] [SCWCD - 94% - Story] [SCBCD - 80% - Story] | My Blog
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39878
    
  28
I presume you are making a simple calculator which returns 9 from 1 + 2 * 3 rather than the mathematically correct answer. To get the correct answer you would probably have to incorporate a parser in the program, which is probably more than the assignment requires. Omar al Kababji is quite right to give hints, but you would be better to create a private or package-private class which implements ActionListener and encapsulates the number too.Then the action can append a 1 to the number in the JLabel.

This sounds very much like a Swing-related question. Moving.
Alex Reynders
Greenhorn

Joined: Nov 16, 2008
Posts: 13
Yes Campbell Ritchie your'e right that is exactly what I'm trying to accomplish. I want my calculator to do the same as the calculator one would find in the applications of windows.

I tried the hints that Omar al Kababji gave me but when I click on e.g. '1' I get an error message that says:
"javax.swing.JButton cannot be cast to java.lang.String" this happens on the lines where this code is - e.g. "sText2 = (String) source;" which can be found in lines 7 and 12 respectively...
I'm know the problem lies within the error message but I do not know how to fix this.



This code is for the number buttons (the rest of the number buttons look the same) -



And this code is for my operators (the rest of the operator buttons look the same) -



Could you please help me to sort out this problem. I do not know what to do from here.




but you would be better to create a private or package-private class which implements ActionListener and encapsulates the number too.

I'm a beginner at Java so please bare with me, I don't know what youv'e tried to explain here?

Thanks
Omar Al Kababji
Ranch Hand

Joined: Jan 13, 2009
Posts: 357
Hi Alex you are getting a cast exception since the evt.getSource() dosen't return a String it returns the object that fired the event, this problem should come from this line of code:

you should use source.getText();

another hint:

1) if you want to make a calculator that is similiar to the windows one then you will have to base your work on the two temporary variables used to hold the operands of the mathmatical operation. so the sequence will be something like these

-- application start
1. user presses numeric buttons (for example: 5)
2. user presses an operator (for examply: +)
3. user inserts another numeric value using the numeric buttons as at (1)
4. user presses the = button and you get the result

2) if you want to use the idea of Campbell Ritchie then all your mathmatical string will be inserted in one line as follows:

-- application start
1. user enters a mathmatical string to be computed (for example: 5 + 3 - 7 * 10)
2. your program gets this string parse it and finds the final result and shows it to the user


i think if you implement your calculator using Campbell Ritchie hint it will be easiear for you, even if the first option seems easier. ;)


(peace)
aniruddha panadare
Greenhorn

Joined: Dec 23, 2008
Posts: 15



hay this program might help you

import java.awt.*;
import java.awt.event.*;

public class ArithmeticCalculator extends Frame implements ActionListener
{
Button on, clear, addn, subn, muln, divn, end, equal;
TextField input;
Panel pan1, pan2;
int no1, no2, ans;
char oper;

public ArithmeticCalculator()
{
pan1 = new Panel();
pan2 = new Panel();

addn = new Button("+");
subn = new Button("-");
muln = new Button("*");
divn = new Button("/");
equal = new Button("=");
end = new Button("Exit");
on = new Button("On");
clear = new Button("Clear");

input = new TextField(20);

pan1.add(addn);
pan1.add(subn);
pan1.add(muln);
pan1.add(divn);
pan1.add(equal);

pan2.add(on);
pan2.add(clear);
pan2.add(end);

setLayout(new BorderLayout());

add(input,"North");
add(pan1,"Center");
add(pan2,"South");

input.setEnabled(false);
addn.setEnabled(false);
subn.setEnabled(false);
muln.setEnabled(false);
divn.setEnabled(false);

addn.addActionListener(this);
subn.addActionListener(this);
muln.addActionListener(this);
divn.addActionListener(this);
equal.addActionListener(this);
end.addActionListener(this);
on.addActionListener(this);
clear.addActionListener(this);

setTitle("Arithmetic Calculator");
setSize(200,120);
setVisible(true);
}

public static void main(String args[])
{
new ArithmeticCalculator();
}

public void actionPerformed(ActionEvent ae)
{
Button btn = (Button)ae.getSource();
if(btn == end)
{
System.exit(0);
}

if(btn == addn || btn == subn || btn == muln || btn == divn)
{
no1 = Integer.parseInt(input.getText());
input.setText("");
input.requestFocus();
oper = btn.getLabel().charAt(0);
}

if(btn == equal)
{
no2 = Integer.parseInt(input.getText());
switch(oper)
{
case '+':
ans = no1 + no2;
break;
case '-':
ans = no1 - no2;
break;
case '*':
ans = no1 * no2;
break;
case '/':
ans = no1 / no2;
break;
}
input.setText(Integer.toString(ans));
}

if(btn == clear)
{
input.setText("");
input.requestFocus();
}

if(btn == on)
{
input.setEnabled(true);
addn.setEnabled(true);
subn.setEnabled(true);
muln.setEnabled(true);
divn.setEnabled(true);
}
}
}
Olivier Legat
Ranch Hand

Joined: Nov 17, 2007
Posts: 176

Yes the way I would do it would be similar to Aniruddha's method. Something like this.



Olly
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39878
    
  28
Please don't supply complete answers like that to assignments. It doesn't help anybody learn at all, and even worse, the modern software used to detect plagiarism may lead to that work being awarded a mark of 0%

Omar al Kababji is correct that you should use a getText() (or similar) method to get the values from a text field or label. But I disagree with Olly's suggestion of using JButtons as the source, for at least two reasons:
  • There is no need to cast; a Button is a Component, and the == operator will work happily on objects of different classes.
  • Using this sort of selection isn't object-oriented programming. You should have a value 1 associated with button1 and 2 associated with button2.
  • But using the titles button1 button2 may be bad style: see the JavaRanch style guide.
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39878
        
      28
    omar al kababji wrote:i think if you implement your calculator using Campbell Ritchie hint it will be easiear for you, even if the first option seems easier. ;)


    (peace)
    Thank you.

    Another possibility: clicking a button can multiply a value by 10, then add the value associated with the button. I shall leave you to work out how to implement that.
    Alex Reynders
    Greenhorn

    Joined: Nov 16, 2008
    Posts: 13
    I now have created the actionPerformed() methods for each of the number buttons
    ("0","1","2","3","4","5","6","7","8","9" as well as ".")

    When I click on one of these buttons the number is shown in the textfield but I can get only one number into the textfield...

    e.g. If I click on button "7" the number 7 is shown, but if I click on button "8", 7 disappear and 8 is shown in the text field.
    Why is this happening.

    Here is the code for my program:



    I really appreciate the help youv'e given me this far, but I'm still struggling.
    Please help me.
    Omar Al Kababji
    Ranch Hand

    Joined: Jan 13, 2009
    Posts: 357


    if you look at your code you set the text using "text.setText(sText2);" which cancels any previous text in the text field so you should do something like this:



    also did you notice that you have a lot of repeated or similar code, can you think for a way to prevent all this repetition and make your code smaller in size ?
    Olivier Legat
    Ranch Hand

    Joined: Nov 17, 2007
    Posts: 176

    Alex although you're code may way work with that technique I wouldn't advice it because you're creating a new ActionListener for each Button (thus using up more memory which is a big issue in program development). In my opinion it's a better idea to have one listener for all the buttons.

    Campbell Ritchie wrote:
    But I disagree with Olly's suggestion of using JButtons as the source, for at least two reasons:
    - There is no need to cast; a Button is a Component, and the == operator will work happily on objects of different classes.
    - Using this sort of selection isn't object-oriented programming. You should have a value 1 associated with button1 and 2 associated with button2.
    But using the titles button1 button2 may be bad style:


    I agree with your first point, that was an unnecessary line. Concerning you're second point however I assume that Alex was naming the buttons according to their positioning instead of the value/nature (if you look at his original code), but yes I agree that it's a bad style.
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39878
        
      28
    I think I said "may be bad style." There is an explanation in the JavaRanch style guide which I quoted earlier. It is natural to write button7 for the button which has a 7 on, but many people would say that is bad style.

    The reason the text is changing from 7 to 8 when you push the buttons is probably because you are using the setText() method; you need to append the number to the existing text. You will have to go through the JLabel/JTextField or whatever API documentation and see whether there are methods which append text.
    Or you would have to get the existing text and append the number to it.
    If you are using anonymous ActionListener classes, make sure they all do something completely different from one another. And there is probably no need to check sources; an anonymous class will take events from one button only.
    Alex Reynders
    Greenhorn

    Joined: Nov 16, 2008
    Posts: 13
    Hi guys, Iv'e managed to get a lot done since the last time I got help from you, and my program looks very different now.

    My calculator program now works fine but there's still some tweaking that need to be done, which I need your help with (again ).

    I'm going to post all of my code so that you can see what it looks like, and then help me from there...

    The things that I'm still struggling with is:

    1. The " +/- " button on the calculator is not working and I'm not sure how the code should look like for this button - (which if the user click once must change the sign to a -
    (negative) and show in the textfield and when clicked again must change back to a + (positive) which is obviuosly not shown.
    The " +/- " button is b14 in my code, operator 5, and must be coded in case 5: in the switch\case statement (line 211).

    2. I must create a menu bar, which I did on lines 14 to 25. The problem is, is that the menu bar isn't showing at all. It looks like its behind the main calculator frame, but I don't
    know how to get it to show. Can you please help me to rectify this problem?

    3. I have to create a dialog box to ask the user for confirmation when he/she wants to exit the program, Iv'e created the window listeners (lines 308 to 344) and then put the
    JOptionPane.showConfirmDialog() with the windowClosing() method (lines 319 to 322) , but when I click on the (X) to close the program,
    the program doesn't ask for any confirmation, why is this??

    I would really appreciate further help from you guys.
    P.S - I think it will be a good idea to copy and paste this code in your IDE to see exactly how this program functions.
    Any other help would also be welcome e.g. - to shorten any code etc.
    Thank you.

    Here is the code:


    Mikko Kohtamäki
    Ranch Hand

    Joined: Dec 13, 2008
    Posts: 112
    for operator "+/-" you can create boolean variable 'isNegative' then... for more i dont have time now, but no matter

    Olivier Legat
    Ranch Hand

    Joined: Nov 17, 2007
    Posts: 176

    For problem 3: Window closing problem.

    Lucky for you I finished my exams so I have the time to help you

    Your class implements the WindowListener class meaning that it's able to use itself to listen to window events. However you're not actually adding a WindowListener to your frame you're only setting the default close operation. I'm not gonna copy/paste the entire code again but here's what's missing:


    To close it check this:
    How to Make Dialogs

    Hope it helps
     
     
    subject: Please need help with calculator program...