Page 1 of 3 123 LastLast
Results 1 to 20 of 42
Like Tree3Likes

Thread: Calculator app

  1. #1
    bodylojohn is offline Member
    Join Date
    Nov 2013
    Posts
    37
    Rep Power
    0

    Default Calculator app

    Hello,

    I have finally reached the final assignment of my Java course. First I will give a detailed description of the assignment:
    - The application should be a JApplet that also can be run as an application
    - The calculator should contain the following buttons: 1,2,3,4,5,6,7,8,9,0,MC,MR,MS,M+,BACKSPACE,CE,C,," ,",".",+,-,*,/,sgrt,%,1/x,=
    - Use javaDoc
    - Make html files that contain JavaDoc
    - Make an executable jar.

    The first thing I want to do is to figure out all of the classes I will have to create. Here starts my problem. Should I make a class for each button on the calculator (because a calculator HAS-A button)?
    And thats where I need a little push in the right direction. How can I determine of what entity to make a class?
    Because there are also the calculations, display in a JTextfield, etc.

    I really hope you can help me determine all of the necessary classes before I even start building.

    This is a cross post to http://www.javaprogrammingforums.com...tml#post142153

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,447
    Blog Entries
    7
    Rep Power
    20

    Default Re: Calculator app

    You have to decide what kind of expressions you want to evaluate: infix expressions, such as 3*(4+5)? or postfix expressions, such as 3 4 5 + *? How are you going to collect entire numbers given the individual digits? What is the CE button supposed to do exactly? Concentrate on that functionality, the silly view part comes later ...

    kind regards,

    Jos
    gimbal2 likes this.
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,895
    Rep Power
    5

    Default Re: Calculator app

    When I was in school I worked from the top-down approach; first I would focus 100% on all the stuff that you can "see", so the user interface and such and then later I would be forced to have to hammer in the actual application, which required me to adapt the user interface I had already made making me lose time and end up with ugly code that had logic of the application and logic of the user interface all mixed up into one huge mess that is hard to follow and hard to make changes to.

    Nowadays I know better - I start with the actual application logic, and I make that work from automated tests ('unit tests', although I call mine 'feature tests' because they're larger than a single unit). Nothing visual about any of that, just me and the code and a large set of validation checks that ensure that what I put in produces the results I expect. When I get everything working as I want it to work, which in this case would be the calculator logic itself as Jos explains, only then do I do the final step which is to put the icing on it; the user interface. At this point if things don't work properly I know it is a flaw in the user interface logic, because I already have test code that proves the application logic works. It makes everything nice and simple and isolated, because through this way of working you won't so easily accidentally mix and mash application code and user interface logic either.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  4. #4
    jashburn is offline Senior Member
    Join Date
    Feb 2014
    Posts
    219
    Rep Power
    1

    Default Re: Calculator app

    Firstly, credits to you for posting this question as it's a very good question for someone new to programming. It's also nice of you to be up-front with the cross-posting.

    Quote Originally Posted by bodylojohn View Post
    How can I determine of what entity to make a class?
    [...]
    I really hope you can help me determine all of the necessary classes before I even start building.
    When I was at uni many years back the software engineering lecturer used the book Applying UML and Patterns by Craig Larman. This book remains as one of my favourite books on OOA and OOD.

    Larman advocates the use of a "conceptual model" for what you're trying to do. This is summarised at http://www.cs.ucc.ie/~adrian/cs560/U...ceptualMod.pdf (PDF slides), including techniques to identify the "concepts". According to the book there are a few more steps to go through before ending up with a class diagram that you can use to start your coding, but let's not get over the top with this... Suffice to say that usually the class diagram would look similar to the conceptual model, so a quick sketch on paper of the conceptual model can help you identify the classes you need as well as the overall static design of your application. I have actually applied this technique in my professional work quite successfully.

    I agree with Jos and gimbal2 that the user interface (view) is of secondary concern. For you at this stage I'd suggest once you have a general design that you're happy with, you can approach it how ever way feels most natural to you. This is from the pragmatic perspective of the finite amount of time you have for your assignment. Just so that you're aware, there are software engineering best practices that encourage the use of Test-Driven Development (TDD; write automated tests before writing application code) and Agile Development (e.g., Scrum, where you implement vertical slices of functionality (user stories) in an iterative manner (sprints), with something demonstrable/usable at the end of each iteration). For a programming assignment, these practices might be an overkill, but in the future if you are to do this professionally, it would be essential for you to know about them.

    Good luck!
    gimbal2 likes this.

  5. #5
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,895
    Rep Power
    5

    Default Re: Calculator app

    You know Scrum is already out of fashion right? ;)

    Funny enough I got a similar lecture with the same book as the base. I find UML a bit of a doubled edged sword. To the right mind it can help to visualize object oriented problems, but most of my classmates were just stuck on "getting the UML right" in stead of really seeing the light because of it. That proved itself the most when at one point in time we had to do a battleship game with full UML diagrams and two of my best mates, quite intelligent chaps, came up to me and asked me "Okay we've got the Board class and the Ship class, now how do we make the classes send messages to each other?"
    jashburn likes this.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  6. #6
    jashburn is offline Senior Member
    Join Date
    Feb 2014
    Posts
    219
    Rep Power
    1

    Default Re: Calculator app

    Quote Originally Posted by gimbal2 View Post
    You know Scrum is already out of fashion right? ;)
    Everything's out of fashion on the following day. :-)

    Quote Originally Posted by gimbal2 View Post
    I find UML a bit of a doubled edged sword. To the right mind it can help to visualize object oriented problems, but most of my classmates were just stuck on "getting the UML right" in stead of really seeing the light because of it.
    That's very true. We must keep in mind that UML is but just a way to communicate ideas. If we can communicate ideas effectively using, say, paper planes, why not? (Yes, UML is supposed to be a "standard" language so that it's easy for everyone to understand what you're trying to convey, but if you work in an organisation that communicates using paper planes...)

    Quote Originally Posted by gimbal2 View Post
    now how do we make the classes send messages to each other?"
    Ah, they would know how to do that once they have completed the System Sequence Diagram and Collaboration Diagram! ;-)

    The takeaway, so as not to confuse bodylojohn, is you can use a conceptual model to help with the general design and to help identify the classes that you are likely to need. UML is used in the book for this, but again, be pragmatic about it. Your UML diagrams don't have to be perfect to be able to write good code, nor is it a requirement to use UML on the first place. (Of course, unless it is a UML assignment...)

  7. #7
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,895
    Rep Power
    5

    Default Re: Calculator app

    Paper airplanes are nice. But me - I just draw blocks and arrows on a piece of paper ;) With a pencil!
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  8. #8
    bodylojohn is offline Member
    Join Date
    Nov 2013
    Posts
    37
    Rep Power
    0

    Default Re: Calculator app

    Could anybody please help me in creating the gui (see image below).
    I already have 3 classes; CalcApplet, CalcApp and Calculator.

    Calculator contains some testcode thats shows a button.
    Java Code:
    import java.awt.*;
    import javax.swing.*;
    
    public class Calculator extends JPanel {
    	public Calculator(){
    	    setLayout( new BorderLayout() );
    	    JPanel mainPanel = new JPanel();
    	    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    	    
    	    
    	    JPanel pDisplay = new JPanel();
    	    pDisplay.setBackground(Color.BLUE);
    	    
    	    JPanel pNummeriek = new JPanel();
    	    pNummeriek.setBackground(Color.GRAY);
    	    
    	    
              mainPanel.add(pDisplay);
    	    mainPanel.add(pNummeriek);
    	    CalcButton t = new CalcButton("Test");
    	    CalcButton q = new CalcButton("Testq");
    	    pDisplay.add(t);
    	    pNummeriek.add(q);
        
    	    add( mainPanel, BorderLayout.CENTER );
    	}
    }
    CalcApplet runs Calculator as an JApplet
    Java Code:
    import java.awt.*;
    import javax.swing.*;
    
    /**
     * <p>Title: 		CalcApplet </p>
     * <p>Description: 	Dit is de calculator welke als applet gerund wordt </p>
     * <p>Copyright: 	Copyright (c) 2014</p>
     * <p>Date: 		14-03-2014 </p>
     * <p>@author  		Johnny Hermes </p>
     * <p>@version		1.0 </p>
     * 
     **/
    public class CalcApplet extends JApplet {
    
    	/**
    	 * <p> Description: Inits the applet</p>
    	 * 
    	 **/	
    	public void init()
    	{
    		// Definieer de layout
    		setLayout( new BorderLayout() );
    		// Definieer de grootte
    		setSize(350, 310);
    		// Voeg een instance toe aan de applet van Calculator
    		add( new Calculator(), BorderLayout.CENTER );
    	
    	}
    
    	
    }
    CalcApp runs Calculator as an Application.
    Java Code:
    /**
     * <p>Title: 		CalcApp </p>
     * <p>Description: 	Dit is de calculator welke als application gerund wordt </p>
     * <p>Copyright: 	Copyright (c) 2014</p>
     * <p>Date: 		14-03-2014 </p>
     * <p>@author  		Johnny Hermes </p>
     * <p>@version		1.0 </p>
     * 
     **/
    
    	import java.awt.*;
    	import java.awt.event.*;
    	
    public class CalcApp {
    	/**
    	* <p> Description: the main method</p>
    	* @param args
    	*/
    	public static void main( String args[] )
    	{
    		// Create a frame
    	   Frame fr = new Frame();
    	   // set the properties of the frame
    	   fr.setTitle( "Awt Calculator" );
    	   fr.setSize( 350, 310 );
    	   fr.setResizable( false );
    	   // add a new instance of AwtCalc to the frame
    	   fr.add( new Calculator(), BorderLayout.CENTER );
    	   //Set the frame visible
    	   fr.setVisible( true );
    	   // add a windowlistener to the frame
    	   fr.addWindowListener( new WindowAdapter() 
    	   {
    	   		/**
    	   		 * Method: windowClosing
    	   		 * <p> Description: This method will close the frame
    	   		 */
    		   public void windowClosing( WindowEvent e )
    	   		{
    	   	   		System.exit( 1 );
    	   		}
    		   });
    		}
    		
    	}
    Calculator app-calculator.jpg

  9. #9
    bodylojohn is offline Member
    Join Date
    Nov 2013
    Posts
    37
    Rep Power
    0

    Default Re: Calculator app

    I got the gui to (almost) look like the image.
    But I don't think I coded optimally.
    Before I continue I would like to optimize the code below.

    Any tips on how to do this?


    Java Code:
    import java.awt.*;
    import javax.swing.*;
    
    public class Calculator extends JPanel {
    	JPanel mainPanel = new JPanel();
    	BoxLayout BoxLayout = new BoxLayout(mainPanel , 1);
    	JPanel displayPanel = new JPanel();
    	JTextField display = new JTextField();
        JPanel topButtonRow = new JPanel();
        JPanel calcPanel = new JPanel();
        GridLayout topButtonRowGrid = new GridLayout();
        GridLayout calcPanelGrid = new GridLayout();
        JButton bMC = new JButton("MC");
        JButton b0 = new JButton("0");
        JButton b1 = new JButton("1");
        JButton b2 = new JButton("2");
        JButton b3 = new JButton("3");
        JButton b4 = new JButton("4");
        JButton b5 = new JButton("5");
        JButton b6 = new JButton("6");
        JButton b7 = new JButton("7");
        JButton b8 = new JButton("8");
        JButton b9 = new JButton("9");
        JButton bDelen = new JButton("/");
        JButton bSqrt = new JButton("sqrt");
        JButton bMR = new JButton("MR");
        JButton bVermenigvuldig = new JButton("*");
        JButton bProcent = new JButton("%");
        JButton bMS = new JButton("MS");
        JButton bMinus = new JButton("-");
        JButton bPrimitieveren = new JButton("1/x");
        JButton bMPlus = new JButton("M+");
        JButton bPlusMin = new JButton("+/-");
        JButton bPunt = new JButton(".");
        JButton bPlus = new JButton("+");
        JButton bIs = new JButton("=");
        JButton bEmpty = new JButton("");
        JButton bBackspace = new JButton("Backspace");
        JButton bCE = new JButton("CE");
        JButton bC = new JButton("C");
            
    	public Calculator(){
    		add( mainPanel);   
    	    mainPanel.setLayout(BoxLayout);
    	    mainPanel.add(displayPanel);
    	    displayPanel.add(display);
    	    display.setColumns(40);
    	    mainPanel.add(topButtonRow);
    	    topButtonRow.setLayout(topButtonRowGrid);
    	    topButtonRowGrid.setRows(1);
    	    topButtonRowGrid.setColumns(4);
    	    topButtonRow.add(bEmpty);
    	    //bEmpty.setText("");
    	    topButtonRow.add(bBackspace);
    	    topButtonRow.add(bCE);
    	    topButtonRow.add(bC);
    	    mainPanel.add(calcPanel);
    	    calcPanel.setName("JCalcPanel");
    	    calcPanel.setLayout(calcPanelGrid);
    	    calcPanelGrid.setRows(4);
    	    calcPanelGrid.setColumns(6);
    	    calcPanel.add(bMC);
    	    calcPanel.add(b7);
    	    calcPanel.add(b8);
    	    calcPanel.add(b9);
    	    calcPanel.add(bDelen);
    	    calcPanel.add(bSqrt);
    	    calcPanel.add(bMR);
    	    calcPanel.add(b4);
    	    calcPanel.add(b5);
    	    calcPanel.add(b6);
    	    calcPanel.add(bVermenigvuldig);
    	    calcPanel.add(bProcent);
    	    calcPanel.add(bMS);
    	    calcPanel.add(b1);
    	    calcPanel.add(b2);
    	    calcPanel.add(b3);
    	    calcPanel.add(bMinus);
    	    calcPanel.add(bPrimitieveren);
    	    calcPanel.add(bMPlus);
    	    calcPanel.add(b0);
    	    calcPanel.add(bPlusMin);
    	    calcPanel.add(bPunt);
    	    calcPanel.add(bPlus);
    	    calcPanel.add(bIs);
    	}
    }

  10. #10
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,895
    Rep Power
    5

    Default Re: Calculator app

    define "optimize". You want to have less 'add' calls? In my experience building a GUI just requires plenty of boilerplate code. You might save a bit of code with a little trick by creating a method which allows you to create a button and add it to the panel right away:

    Java Code:
    public JButton addButton(JButton button){
       calcPanel.add(button);
       return button;
    }
    
    JButton b0 = addButton(new JButton("0"));
    And a little tip: use English variable names. The language is also based on English, if you then start to mix in Dutch you only create something which makes your brain have to switch contexts constantly, and it becomes harder to read in international places such as this forum.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  11. #11
    bodylojohn is offline Member
    Join Date
    Nov 2013
    Posts
    37
    Rep Power
    0

    Default Re: Calculator app

    @gimbal2: Thank you very much.
    You are totally right. I will use English from now on!

  12. #12
    bodylojohn is offline Member
    Join Date
    Nov 2013
    Posts
    37
    Rep Power
    0

    Default Re: Calculator app

    Now that I covered some of the gui stuff it's time to look at the actual functionality of the calculator.
    I suppose I have to create a string that will contain the inputs from the calculator, example: "2 + 6 - 4 *2 / 2"
    Or am I totally wrong here?

  13. #13
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,895
    Rep Power
    5

    Default Re: Calculator app

    Its your application dude, you know what you want don't you? ;)
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  14. #14
    bodylojohn is offline Member
    Join Date
    Nov 2013
    Posts
    37
    Rep Power
    0

    Default Re: Calculator app

    Quote Originally Posted by gimbal2 View Post
    Its your application dude, you know what you want don't you? ;)
    To be honest I am totally stuck on this.
    Building the windows calculator is the last assignment and then I am done with the course.

  15. #15
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,895
    Rep Power
    5

    Default Re: Calculator app

    That's regrettable, because hanging around in this forum is not going to change that; you still need to get yourself to the point where you can progress yourself.

    When I look at what you want to achieve I see at least two classes: a Calculation class which contains zero or more parts, and a CalculationPart class which represents one of the parts of the calculation. Given the example, that would be the following parts:

    2
    +6
    -4
    * 2
    / 2

    The toString() of Calculation produces the entire formula in one go. That's the easy part.

    You also need to be able to "execute" the calculation to get the result. That has one major and epic challenge: order of execution, you can't just blindly evaluate it from left to right. That is going to be quite a puzzle to implement. I would not jump into code, try to work something out with pencil and paper first.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  16. #16
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,447
    Blog Entries
    7
    Rep Power
    20

    Default Re: Calculator app

    Quote Originally Posted by bodylojohn View Post
    To be honest I am totally stuck on this.
    Building the windows calculator is the last assignment and then I am done with the course.
    You should've thought about this when you were building the controller and the model parts of your calculator (as advised). You can't just 'hack it in' as an afterthought ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  17. #17
    jashburn is offline Senior Member
    Join Date
    Feb 2014
    Posts
    219
    Rep Power
    1

    Default Re: Calculator app

    Quote Originally Posted by bodylojohn View Post
    I suppose I have to create a string that will contain the inputs from the calculator, example: "2 + 6 - 4 *2 / 2"
    You may have a get-out-of-jail-free card. It seems that it may not be necessary to capture the entire expression into a string to be parsed if what you're doing is to emulate WC (Windows Calculator). (Note: I've download Windows Calculator Plus and am running it using Wine on Linux, but I'm assuming the behaviour of Calculator Plus is the same as the original WC.)

    The evaluation of "2 * 4 + 6 / 2", taking into account operator precedence, gives you a result of 11 based on the calculation of (2 * 4) + (6 / 2). However if you enter that directly into WC you'll get a result of 7. This is because with each press of an operator (+, -, * and /) button WC evaluates the preceding expression before applying the operator to the result. In other words, the calculation in WC proceeds as follows:

    Key press Display on screen
    2 2
    * 2
    4 4
    + 8 (evaluates 2 * 4 here)
    6 6
    / 14 (evaluates 8 + 6 here)
    2 2
    = 7 (evaluates 14 / 2 here)

    WC under Standard mode doesn't allow you to use brackets, and so calculation proceeds left-to-right without operator precedence.

    At first look it seems that you only need to keep track of 2 things:
    1. the last result
    2. operator applied

    With every operator key press, you'll need to update the result before applying the operator, and then wait for the next number's key press(es).

    The treatment for the other operators is different - for you to discover - but I don't think you need to worry about operator precedence.

  18. #18
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,447
    Blog Entries
    7
    Rep Power
    20

    Default Re: Calculator app

    Quote Originally Posted by jashburn View Post
    The treatment for the other operators is different - for you to discover - but I don't think you need to worry about operator precedence.
    I think it is better to worry about an operator precedence implementation for a while, or otherwise the OP ends up with that idiotic WC evaluation scheme; operator precedence implementations have been done many times before in several ways; for an example of this anyone can read my blog artice (see the link in the top/right corner of this reply) about proper expression parsing and compilation; it even comes with source code; that WC junk really is a nono ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  19. #19
    jashburn is offline Senior Member
    Join Date
    Feb 2014
    Posts
    219
    Rep Power
    1

    Default Re: Calculator app

    Quote Originally Posted by JosAH View Post
    I think it is better to worry about an operator precedence implementation for a while, or otherwise the OP ends up with that idiotic WC evaluation scheme
    Well, I did abbreviate it as WC... ;-)

    This is when I apply the very important "Tree-Swing Principle". bodylojohn will need to clarify the main requirement of the assignment; is it to write a WC emulator in Java (for both UI and function)? If so, then we wouldn't want to design it the way the Tree-Swing Analyst would by introducing operator precedence, otherwise the outcome will not meet the requirement. If it is not to functionally emulate WC, then get clarification on operator precedence. The instructor may still opt for the WC way to simplify things if the focus of this assignment is in software design rather than algorithm writing.

    Quote Originally Posted by JosAH View Post
    for an example of this anyone can read my blog artice (see the link in the top/right corner of this reply) about proper expression parsing and compilation; it even comes with source code
    That's a great article! There are also other ways to evaluate an arithmetic expression such as those described at eval() in java? | Sudhakar Rayavaram Blog and 3 method to evaluate expressions in Java | David Euler on coding and design. (My favourite cheat is to use Java's JavaScript engine's eval()...)

    So, bodylojohn, what's the requirement? WC or not?

  20. #20
    gauravbhusare is offline Member
    Join Date
    Mar 2014
    Posts
    1
    Rep Power
    0

    Default Re: Calculator app

    This is a great article...
    It shows lots of functionality of calculators back end..

Page 1 of 3 123 LastLast

Similar Threads

  1. BMI calculator
    By snustad in forum New To Java
    Replies: 4
    Last Post: 11-29-2012, 09:08 PM
  2. Need help with + - * / calculator
    By Aconitum in forum New To Java
    Replies: 26
    Last Post: 08-04-2012, 07:13 PM
  3. Need help with Calculator
    By Joshua4missions in forum New To Java
    Replies: 4
    Last Post: 12-10-2011, 02:44 AM
  4. Help in a calculator
    By Ayannie in forum New To Java
    Replies: 6
    Last Post: 01-04-2011, 08:21 PM
  5. help with calculator
    By kalibballer in forum New To Java
    Replies: 8
    Last Post: 04-01-2009, 12:57 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •