• RSS
  • Twitter
  • FaceBook

Security Forums

Log in

FAQ | Search | Usergroups | Profile | Register | RSS | Posting Guidelines | Recent Posts

calculator

Users browsing this topic:0 Security Fans, 0 Stealth Security Fans
Registered Security Fans: None
Goto page 1, 2  Next
Post new topic   Reply to topic   Printer-friendly version    Networking/Security Forums Index -> Programming and More

View previous topic :: View next topic  
Author Message
kissda
Just Arrived
Just Arrived


Joined: 18 Jan 2005
Posts: 0


Offline

PostPosted: Mon Dec 12, 2005 12:04 am    Post subject: calculator Reply with quote

I am trying to add a decimal function to the following calculator program that I made. Can it be done?

Code:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;


public class Calc extends java.applet.Applet implements ActionListener{
   
   TextField Answer;
   Button Plus;
   Button Minus;
   Button Multiply;
   Button Divide;
   Button Percent;
   Button Equals;
   Button Clear;
   int Save = 0;
   char oper = '=';
   char lastoper = '=';
   boolean Num = true;
   
   
    public void init() {
     
      Answer = new TextField("0",5);
      Panel AnswerPanel = new Panel();
      AnswerPanel.add(Answer);
      Panel NumPanel = new Panel();
      NumPanel.setLayout(new GridLayout(4,5,2,2));
      Panel opPanel = new Panel();
      opPanel.setLayout(new GridLayout(4,4,2,2));
         
      for (int i = 0; i <= 9; i++){
         Button aNum=new Button(Integer.toString(i));
         aNum.addActionListener (this);
         NumPanel.add(aNum);
         add(NumPanel);
      }
         
      Plus=new Button("+");
      Minus=new Button("-");
      Multiply=new Button("*");   
      Divide=new Button("/");     
      Percent=new Button("%");
      Equals=new Button("=");     
      Clear=new Button("C");     
      Plus.addActionListener(this);           
      Minus.addActionListener(this);     
      Multiply.addActionListener(this);
      Divide.addActionListener(this);     
      Percent.addActionListener(this);
      Equals.addActionListener(this);     
      Clear.addActionListener(this);
      opPanel.add(Plus);
      opPanel.add(Minus);
      opPanel.add(Multiply);
      opPanel.add(Divide);
      opPanel.add(Percent);
      opPanel.add(Decimal);
      opPanel.add(Equals);
      opPanel.add(Clear);
      add(opPanel);
      Panel All = new Panel();
        All.setLayout(new BorderLayout(2,2));
        All.add(AnswerPanel, BorderLayout.NORTH );
        All.add(opPanel, BorderLayout.WEST );
        All.add(NumPanel , BorderLayout.CENTER);
       add(All);
   }
   
   public void actionPerformed(ActionEvent event) {
     
      if (event.getActionCommand() instanceof String) {
         String string = (String) event.getActionCommand();
         if (string.charAt(0) >= '0' && string.charAt(0) <= '9') {
            if (Num)
               Answer.setText(string);
            else
               Answer.setText(Answer.getText() + string);
            Num = false;
         }
         else {
            if (string.charAt(0) == '-' && Num) {
               Answer.setText("-");
               Num = false;
            }
            else {
               oper = string.charAt(0);
               calculator(Integer.parseInt(Answer.getText()));
               Num = true;
            }
            lastoper = oper;
         }
      }
      return;
   }
   public void calculator(int a){
     
      switch (oper){
         case '+':
         case '-' :
         case '*':
         case '/':
         case '%':
         Save = a;
         return;
      }
      if (oper == '=')
         oper = lastoper;
      switch (oper) {
         case '+' :
         Save += a;
         break;
         case '-':
         Save -= a;
         break;
         case '*':
         Save *= a;
         break;
         case '/' :
         Save /= a;
         break;
         case '%':
         Save %= a;
         break;
         case 'C':
         Save = 0;
         break;
      }
      Answer.setText("" + Save);
   }
}


Last edited by kissda on Tue Dec 13, 2005 2:30 am; edited 2 times in total
Back to top
View user's profile Send private message
Groovicus
Trusted SF Member
Trusted SF Member


Joined: 19 May 2004
Posts: 9
Location: Centerville, South Dakota

Offline

PostPosted: Mon Dec 12, 2005 1:07 am    Post subject: Reply with quote

That shouldn't be too much of a problem. You just need to change three lines to make it accept doubles Wink. Then add a button and listener.

One thing you need to consider is that you have an overflow issue in its current version. Try multiplying 999999999 * 999999999.. I got zero. You may want to consider some code that notices if a number is too big to display in the window (or goes beyond the bounds of an int) and somehow have it handle it.
Back to top
View user's profile Send private message Visit poster's website
kissda
Just Arrived
Just Arrived


Joined: 18 Jan 2005
Posts: 0


Offline

PostPosted: Mon Dec 12, 2005 1:21 am    Post subject: Reply with quote

A double, lol and for some reason I was thinking it may be something to do with a float. Double had never even crossed my mind.

I think i need to change all the ints to doubles, is that right? where abouts should i add them?

I hadnt tried 999999999 * 999999999, i see your point now. the book never even mentioned it Sad
Back to top
View user's profile Send private message
Groovicus
Trusted SF Member
Trusted SF Member


Joined: 19 May 2004
Posts: 9
Location: Centerville, South Dakota

Offline

PostPosted: Mon Dec 12, 2005 1:34 am    Post subject: Reply with quote

Quote:
I hadnt tried 999999999 * 999999999

Books rarely mention things like that, but you do need to consider what happens when a user provides input.. like what happens if I try typing abcde + hijkl... It is a good habit to get into, though, while your programs are still simple. Thaen when you start doing more complex programs, you won't have to think so hard about making your code user friendly. For instance, if I expect a user to put numbers in somewhere, I automatically know I have to check and make sure that they didn't try to input something else. I'm not sure how far along you are skill wise, but there are a number of methods that you could use. Try/catch blocks are probably the easiest. Regular Expression matching is pretty easy.

Now, as far as adding doubles.. you don't need to add anythihng. You just need to change what you already have... look at the method that is handling the calculations... look at the number that is being saved,.. and look at what is being parsed. Java is so regular that you should be able to figure out without too much trouble what needs to be changed. Smile
Back to top
View user's profile Send private message Visit poster's website
kissda
Just Arrived
Just Arrived


Joined: 18 Jan 2005
Posts: 0


Offline

PostPosted: Mon Dec 12, 2005 1:59 am    Post subject: Reply with quote

I got most of it working fine now. It's using the doubles fine, when i input 6 + 4 = 10.0. I had trouble geting the clear function working again but its fine now. Just having difficulty getting the decimal button to add a decimal when its pressed. using case like the rest of the buttons (+,/,-,etc) doesnt work. any ideas?

thanks for the help Smile
Back to top
View user's profile Send private message
Groovicus
Trusted SF Member
Trusted SF Member


Joined: 19 May 2004
Posts: 9
Location: Centerville, South Dakota

Offline

PostPosted: Mon Dec 12, 2005 2:18 am    Post subject: Reply with quote

The decimal should get added just like any of the numbers... It isn't a case like the arithmetic functions. How do you append a string of numbers together?
Back to top
View user's profile Send private message Visit poster's website
kissda
Just Arrived
Just Arrived


Joined: 18 Jan 2005
Posts: 0


Offline

PostPosted: Mon Dec 12, 2005 4:20 am    Post subject: Reply with quote

I've been trying for awhile now and I just can't come up with anything that works at all. I was thinking this would work...

Code:

 if (event.getSource() == Decimal) {
    oper = Integer.parseInt(Answer.getText());
      Answer.setText(".");


but i dont even think i'm close. How would i actually do it?
Back to top
View user's profile Send private message
Groovicus
Trusted SF Member
Trusted SF Member


Joined: 19 May 2004
Posts: 9
Location: Centerville, South Dakota

Offline

PostPosted: Mon Dec 12, 2005 4:53 am    Post subject: Reply with quote

Ok, first of all, you are not parsing an int.... it is now a double (that is, if you changed everything to accept decimals).

This bit of code here from the original program:
Code:
if (string.charAt(0) >= '0' && string.charAt(0) <= '9') {
            if (Num)
               Answer.setText(string);
            else
               Answer.setText(Answer.getText() + string);
            Num = false;
         }


This bit of code seems to do the following.. when a button is pushed, and if that button is greater than or equal to zero, and if that button is less than or equal to 9, then add the number to the string of text that is already displayed.

Again, the decimal point is not an operator. You want to treat it just like one of the numbers.

So, thinking through this logically....
Code:

if the button pushed is a number, then add it to the string of numbers.
if it is a decimal point, add the decimal point to the string of numbers.
if it is an operator, do the operation and display the output...


So, I type a 9, and 9 appears in the window. Then I push 1, and 91 appears in the window. Then I push . and 91. appears in the window. Etc, etc.

So looking at the code snippet you just posted...let's see what you are doing.
Code:
if (event.getSource() == Decimal) {
    oper = Integer.parseInt(Answer.getText());
      Answer.setText(".");


First, I (being the program) check to see if the button pushed is a Decimal; I parse the contents of the text field into an Int. Then I display a '.' in the text field without the number...

Think about that for a minute... why would you want to parse the number? And if you think about it, you wouldn't want to parse it to an int anyway. We have to work with doubles in order to use decimals.... Don't you suppose that since it is text that you are getting from the textfield, wouldn't you just want to add a decimal to the string? The only time you need to parse the text is when an operator has been pressed. Once an operator has been pressed, then you want to parse the text so that the proper arithmetic operation can be done.

I don't know how much more of a hint I can give you without giving the whole thing away, because you already know what to do. You have already done it with the textfield string.
Back to top
View user's profile Send private message Visit poster's website
kissda
Just Arrived
Just Arrived


Joined: 18 Jan 2005
Posts: 0


Offline

PostPosted: Mon Dec 12, 2005 9:48 pm    Post subject: Reply with quote

I see the logic in what your saying, but the actually doing it part is really tough. Here's the code with the double and decimal.

Code:


         if (event.getSource() == Decimal){
         Answer.setText(Answer.getText() string + '.');
         }


   


What happens when I use the decimal button now is if its pressed after I've clicked a number button it will display "0.0."
what have I done wrong? I've got no actual idea were to actually put the decimal code in. Havent been this frustrated in a long while Confused

Code:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;


public class Calc extends java.applet.Applet implements ActionListener{
   
   TextField Answer;
   Button Plus;
   Button Minus;
   Button Multiply;
   Button Divide;
   Button Percent;
   Button Equals;
   Button Clear;
   Button Decimal;
   double Save = 0;
   char oper = '=';
   char lastoper = '=';
   boolean Num = true;
   
   
    public void init() {
     
      Answer = new TextField("0",5);
      Panel AnswerPanel = new Panel();
      AnswerPanel.add(Answer);
      Panel NumPanel = new Panel();
      NumPanel.setLayout(new GridLayout(4,5,2,2));
      Panel opPanel = new Panel();
      opPanel.setLayout(new GridLayout(4,4,2,2));
         
      for (int i = 0; i <= 9; i++){
         Button aNum=new Button(Integer.toString(i));
         aNum.addActionListener (this);
         NumPanel.add(aNum);
         add(NumPanel);
      }
         
      Plus=new Button("+");
      Minus=new Button("-");
      Multiply=new Button("*");   
      Divide=new Button("/");     
      Percent=new Button("%");
      Decimal=new Button(".");
      Equals=new Button("=");     
      Clear=new Button("C");     
      Plus.addActionListener(this);            Minus.addActionListener(this);     
      Multiply.addActionListener(this);
      Divide.addActionListener(this);     
      Percent.addActionListener(this);
      Decimal.addActionListener(this);
      Equals.addActionListener(this);     
      Clear.addActionListener(this);
      opPanel.add(Plus);
      opPanel.add(Minus);
      opPanel.add(Multiply);
      opPanel.add(Divide);
      opPanel.add(Percent);
      opPanel.add(Decimal);
      opPanel.add(Equals);
      opPanel.add(Clear);
      add(opPanel);
      Panel All = new Panel();
        All.setLayout(new BorderLayout(2,2));
        All.add(AnswerPanel, BorderLayout.NORTH );
        All.add(opPanel, BorderLayout.WEST );
        All.add(NumPanel , BorderLayout.CENTER);
       add(All);
   }
   
   public void actionPerformed(ActionEvent event) {
     
      if (event.getActionCommand() instanceof String) {
         String string = (String) event.getActionCommand();
         if (string.charAt(0) >= '0' && string.charAt(0) <= '9' ) {
            if (Num)
               Answer.setText(string);
            else
               Answer.setText(Answer.getText() + string);
            Num = false;
         }
         else {
            if (string.charAt(0) == '-' && Num) {
               Answer.setText("-");
               Num = false;
            }
            else {
               oper = string.charAt(0);
               calculator(Double.parseDouble(Answer.getText()));
               Num = true;
            }
            lastoper = oper;
         }
      }

/////////////////////////////Decimal part
         if (event.getSource() == Decimal){
         Answer.setText(Answer.getText() string + '.');
         }
//////////////////////////////
      return;
   }
   public void calculator(double a){
     
      switch (oper){
         case '+':
         case '-' :
         case '*':
         case '/':
         case '%':
         Save = a;
         return;
      }
      if (oper == '=')
         oper = lastoper;
      switch (oper) {
         case '+' :
         Save += a;
         break;
         case '-':
         Save -= a;
         break;
         case '*':
         Save *= a;
         break;
         case '/' :
         Save /= a;
         break;
         case '%':
         Save %= a;
         break;
         case 'C':
         Save = 0;
         break;
      }
      Answer.setText("" + Save);
   }
}

If I'm not even close, what should I have done?
thanks for your help, you really should write a book because you have been one billion times more helpful than this book Smile


Last edited by kissda on Tue Dec 13, 2005 2:31 am; edited 2 times in total
Back to top
View user's profile Send private message
Groovicus
Trusted SF Member
Trusted SF Member


Joined: 19 May 2004
Posts: 9
Location: Centerville, South Dakota

Offline

PostPosted: Mon Dec 12, 2005 10:07 pm    Post subject: Reply with quote

The problem is that you are still trying to treat it as something other than a bit of text that appears in the textfield.

You have this bit of code
Code:

if (string.charAt(0) >= '0' && string.charAt(0) <= '9') {
            if (Num)
               Answer.setText(string);
            else
               Answer.setText(Answer.getText() + string);
            Num = false;
                     
         }         


This piece of code says: if the button pushed is a number, take the string that is displayed in the textfield, and add the new number to it, and display the new number in the textfield... remember at this point, your number is really just a string....

I wonder what would happen if in your condtional check it said "If the charAt(0) is <= and the charAt(0) is >=0 , or charAt(0) is a decimal"...

What do you suppose would happen? Maybe I have not pointed it out to you, although I have really tried, is that you already have the code in place.. it just needs to be modified slightly. You almost have it...

Get rid of that other conditional check...
Code:

/////////////////////////////Decimal part
         if (event.getSource() == Decimal){
         Answer.setText(Answer.getText() string + '.');
         }
//////////////////////////////


You don't need it.

Quote:
thanks for your help, you really should write a book because you have been one billion times more helpful than this book
Embarassed

I have an instructor that goes through things line by line like that. He won't tell you what to do, but he will explain what your code is doing, as opposed to what you think your code is doing.... maybe some of that rubbed off. Smile At any rate, I think it is one of the best ways to learn.
Back to top
View user's profile Send private message Visit poster's website
kissda
Just Arrived
Just Arrived


Joined: 18 Jan 2005
Posts: 0


Offline

PostPosted: Mon Dec 12, 2005 10:32 pm    Post subject: Reply with quote

Ahh I see what you mean now, something like this...

Code:

if (string.charAt(0) <= '9' && string.charAt(0) >= '0' || string.charAt(0) = '.')

or
Code:

if (string.charAt(0) <=  && string.charAt(0) >=0 || string.charAt(0) = '.')


I havent actually had a chance to use 'or' yet in any code. If I use either of these lines instead of the original, it pumps errors at me when I try to compile... "illegal start of expression" and "')' expected". Is this any better?

edit... actually with the first one I only get one error...operator || cannot be applied to boolean,char
Back to top
View user's profile Send private message
Groovicus
Trusted SF Member
Trusted SF Member


Joined: 19 May 2004
Posts: 9
Location: Centerville, South Dakota

Offline

PostPosted: Tue Dec 13, 2005 1:15 am    Post subject: Reply with quote

Heh.. now for the next important lesson..

Code:

if (string.charAt(0) <= '9' && string.charAt(0) >= '0' || string.charAt(0) = '.')


Your code says if <=9 or >=0, then make string.charAt(0) equal to '.' That isn't what you want to do.. you want to say if string.charAt(0) equals ','

Now, how to explain this.. errm.. the = sign is an assignment operator. For example i =1, b =2, etc. What you really want in there is a comparison operator. Look here:
http://www.superbase.com/langref/ops_comparison.html
And you should be able to figure out what you are doing wrong. BTW, this is a very common mistake for people just beginning programming.
Back to top
View user's profile Send private message Visit poster's website
kissda
Just Arrived
Just Arrived


Joined: 18 Jan 2005
Posts: 0


Offline

PostPosted: Tue Dec 13, 2005 2:32 am    Post subject: Reply with quote

Hey thanks for all your help, I got it working now Smile
Can you recommend any other books to get started in java, maybe some sites? the book I have now is due back to the libary now and I havent been to impressed with it.
Back to top
View user's profile Send private message
Groovicus
Trusted SF Member
Trusted SF Member


Joined: 19 May 2004
Posts: 9
Location: Centerville, South Dakota

Offline

PostPosted: Tue Dec 13, 2005 2:57 am    Post subject: Reply with quote

I can't think of any books that really hold your hand. I wouldn't be too hard on yourself though. This was a reasonably sophisticated program, and you managed to modify it. I'd say all in all you did quite well.

I also can't really recommend any websites. Most of the websites I know of are full of elitist assholes that can't be bothered to really help, or do really bad coding, or have no idea about good structure. I think probably the best place to learn Java online is by using Sun's tutorials. The start of the trail is here:
http://java.sun.com/docs/books/tutorial/getStarted/application/index.html

Getting used to object oriented programming and the idea of classes takes a bit to get your head wrapped around, so you will need to ask alot of questions. Have you done any coding on your own? Do you know what the various parts of a java program are? I could maybe suggest some more improvements for your calculator to make it harder for users to break, or I could suggest a few projects to help learn some basic syntax, but other than that, you are really on your own as far as what you can find for tutorials.
Back to top
View user's profile Send private message Visit poster's website
kissda
Just Arrived
Just Arrived


Joined: 18 Jan 2005
Posts: 0


Offline

PostPosted: Tue Dec 13, 2005 3:16 am    Post subject: Reply with quote

Doh, didnt think of sun's site, thanks. I understand structure slightly, I guess I have a basic understanding of various parts of java programs.
The calculator was mostly my code, the book taught me about the number button array, and basic user input/output and then had an exercise at the end of the chapter to make my own calculator like the windows one but basic.
I've actually had fun making the calculator, using the book and other resources to get the best results. I'm open to any suggestions Smile
Back to top
View user's profile Send private message
Groovicus
Trusted SF Member
Trusted SF Member


Joined: 19 May 2004
Posts: 9
Location: Centerville, South Dakota

Offline

PostPosted: Tue Dec 13, 2005 3:48 am    Post subject: Reply with quote

A couple of changes that I would make to your calculator...

-I'm sure you have discovered already that you can type directly into the textfield. Make the textField non-editable so that users can not do that (easy)

-change the colors of the buttons, text, and background. Use a different font other than the default. (easy to medium)

-since your textField can only display a certain amount of digits, check the output when totalled, and if it is larger than can be displayed in the textfield, convert it to scientific notation. This will cause another problem that will have to be addressed though. Wink (hard)

******

Or, if you are tired of working on your calculator, try this:

Use a JOptionPane to get the following input from a user: a word, a number, a word (for example: dog 2 cat ). Verify that the input is in that order. If it isn't in that order, use a JOptionPane to show them what the error is, and restart.

If the input is correct, print out in a JOptionPane:
"The first word is:" <word1>
"Your number is :"<number>
"Your second word is:"<word2>

******

If that is too simple, then maybe you are ready to learn about stacks, and how to use them.
Back to top
View user's profile Send private message Visit poster's website
Display posts from previous:   

Post new topic   Reply to topic   Printer-friendly version    Networking/Security Forums Index -> Programming and More All times are GMT + 2 Hours
Goto page 1, 2  Next
Page 1 of 2


 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

Community Area

Log in | Register