Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 19 of 19

Thread: Simple Calculator HELP

  1. #1
    Junior Member
    Join Date
    Apr 2014
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Exclamation Simple Calculator HELP

    I need help with my getDisplayValue() method. I am trying to iterate though an Array to display a value in a calculator, but I doesn't work. I keep on getting these weird magical numbers at the end of the iteration. Note that this is done in BlueJ. Thank you for all your help in advance.
    Calculator -> UserInterface -> CalcEngine and Calculator -> CalcEngine.
    public class CalcEngine
    {
        //Instance variables used.
        //These are all the instance variables I used to implement
        //a complete calculator solution. 
     
        private int finalNumber; //Holds results of calculations to date.
        private int[] digitHold; //holds numbers pressed until they are operated on
        private int indexed;  //holds index of last number added to digitHold array
        int currentOp; //indicates operation waiting to be calculated(0=none, 1=plus, 2=minus)
     
        /**
         * Create a CalcEngine instance. Initialise its state so that it is ready 
         * for use.
         */
        public CalcEngine()
        {
            int finalNumber = 0;
            int indexed = 0;
            int currentOp = 0;
            digitHold = new int[10];
        }
     
        /**
         * A number button was pressed. Do whatever you have to do to handle it.
         * The number value of the button is given as a parameter.
         */
        public void numberPressed(int number)
        {
            digitHold[indexed] = number;
            indexed++;
        }
     
        /**
         * Return the value that should currently be displayed on the calculator
         * display. THIS ONE!!:confused::confused:
         */
        public int getDisplayValue()
        {
            int placeValue = 1;
            for(int index = digitHold.length-1; index >= 0; index--)
            {
                finalNumber += digitHold[index] * placeValue;
                placeValue = placeValue * 10;
            }
            return finalNumber/10; //for compilation purposes only
        }
     
        /**
         * The 'plus' button was pressed. 
         */
        public void plus()
        {
     
        }
     
        /**
         * The 'minus' button was pressed.
         */
        public void minus()
        {
            // doesn"t work sequentially.
        }
     
        /**
           * The '=' button was pressed.
         */
        public void equals()
        {
        }
     
        /**
         * The 'C' (clear) button was pressed.
         */
        public void clear()
        {
            finalNumber = 0;
            indexed = 0;
            currentOp = 0;
            for(int index = 0; index < 10; index++)
            {
                digitHold[index] = 0;
            }
            getDisplayValue();
     
        }
     
        /**
         * Return the title of this calculation engine.
         */
        public String getTitle()
        {
            return "Basic Calculator";
        }
     
        /**
         * Return the author of this engine. This string is displayed as it is,
         * so it should say something like "Written by H. Simpson".
         */
        public String getAuthor()
        {
            return "Written by ";
        }
     
        /**
         * Return the version number of this engine. This string is displayed as 
         * it is, so it should say something like "Version 1.1".
         */
        public String getVersion()
        {
            return "Version 1.1";
        }
     
    }
    Next class:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
     
    public class UserInterface
    	implements ActionListener
    {
    	private CalcEngine calc;
    	private boolean showingAuthor;
     
        private JFrame frame;
    	private JTextField display;
    	private JLabel status;
     
    	/**
    	 * Create a user interface for a given calcEngine.
    	 */
    	public UserInterface(CalcEngine engine)
    	{
    		calc = engine;
    		showingAuthor = true;
    		makeFrame();
    		frame.setVisible(true);
    	}
     
    	/**
    	 * Make this interface visible again. (Has no effect if it is already
    	 * visible.)
    	 */
        public void setVisible(boolean visible)
    	{
    		frame.setVisible(visible);
    	}
     
    	/**
    	 * Make the frame for the user interface.
    	 */
    	private void makeFrame()
    	{
    		frame = new JFrame(calc.getTitle());
     
    		JPanel contentPane = (JPanel)frame.getContentPane();
    		contentPane.setLayout(new BorderLayout(8, 8));
    		contentPane.setBorder(new EmptyBorder( 10, 10, 10, 10));
     
    		display = new JTextField();
    		contentPane.add(display, BorderLayout.NORTH);
     
    		JPanel buttonPanel = new JPanel(new GridLayout(4, 4));
    			addButton(buttonPanel, "7");
    			addButton(buttonPanel, "8");
    			addButton(buttonPanel, "9");
    			addButton(buttonPanel, "C");
    			addButton(buttonPanel, "4");
    			addButton(buttonPanel, "5");
    			addButton(buttonPanel, "6");
    			addButton(buttonPanel, "?");
    			addButton(buttonPanel, "1");
    			addButton(buttonPanel, "2");
    			addButton(buttonPanel, "3");
    			buttonPanel.add(new JLabel(" "));
    			addButton(buttonPanel, "0");
    			addButton(buttonPanel, "+");
    			addButton(buttonPanel, "-");
    			addButton(buttonPanel, "=");
    		contentPane.add(buttonPanel, BorderLayout.CENTER);
     
    		status = new JLabel(calc.getAuthor());
    		contentPane.add(status, BorderLayout.SOUTH);
     
    		frame.pack();
    	}
     
    	/**
    	 * Add a button to the button panel.
    	 */
    	private void addButton(Container panel, String buttonText)
    	{
    		JButton button = new JButton(buttonText);
    		button.addActionListener(this);
    		panel.add(button);
    	}
     
    	/**
    	 * An interface action has been performed. Find out what it was and
    	 * handle it.
    	 */
    	public void actionPerformed(ActionEvent event)
    	{
    		String command = event.getActionCommand();
     
    		if(command.equals("0") ||
    		   command.equals("1") ||
    		   command.equals("2") ||
    		   command.equals("3") ||
    		   command.equals("4") ||
    		   command.equals("5") ||
    		   command.equals("6") ||
    		   command.equals("7") ||
    		   command.equals("8") ||
    		   command.equals("9"))
    		{
    			int number = Integer.parseInt(command);
    			calc.numberPressed(number);
    		}
    		else if(command.equals("+"))
    			calc.plus();
    		else if(command.equals("-"))
    			calc.minus();
    		else if(command.equals("="))
    			calc.equals();
    		else if(command.equals("C"))
    			calc.clear();
    		else if(command.equals("?"))
    			showInfo();
     
    		redisplay();
    	}
     
    	/**
    	 * Update the interface display to show the current value of the 
    	 * calculator.
    	 */
    	private void redisplay()
    	{
    		display.setText("" + calc.getDisplayValue());
    	}
     
    	/**
    	 * Toggle the info display in the calculator's status area between the
    	 * author and version information.
    	 */
    	private void showInfo()
    	{
    		if(showingAuthor)
    			status.setText(calc.getVersion());
    		else
    			status.setText(calc.getAuthor());
     
    		showingAuthor = !showingAuthor;
    	}
    }
    Next class:
    public class Calculator
    {
    	private CalcEngine engine;
    	private UserInterface gui;
     
    	/**
    	 * Create a new calculator and show it.
    	 */
    	public Calculator()
    	{
    		engine = new CalcEngine();
    		gui = new UserInterface(engine);
    	}
     
    	/**
    	 * In case the window was closed, show it again.
    	 */
    	public void show()
    	{
    		gui.setVisible(true);
    	}
    }
    Last edited by krowley; April 20th, 2014 at 07:31 PM.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Simple Calculator HELP

    Please edit your post and wrap your code with code tags:
    [code=java]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    krowley (April 20th, 2014)

  4. #3
    Junior Member
    Join Date
    Apr 2014
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Simple Calculator HELP

    Okay. I am new. Thank you!

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Simple Calculator HELP

    I keep on getting these weird magical numbers
    Can you copy them and paste them here.

    One problem I see is that the value returned by the getDisplayValue() method is not saved in a variable.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #5
    Junior Member
    Join Date
    Apr 2014
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Simple Calculator HELP

    When I press 9 I get: 41006540
    8:-58993459
    7:-158993459
    6:170503270
    5:70503270
    4:-29496729
    3:-129496729
    2:200000000
    1:100000000
    0:0

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Simple Calculator HELP

    Ok, what numbers where you expecting instead of those?
    If you don't understand my answer, don't ignore it, ask a question.

  8. #7
    Junior Member
    Join Date
    Apr 2014
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Simple Calculator HELP

    The actual numbers in-putted. This whole point of my project is to create a simple calculator. I should be able to input the number 123 and actually get 123. I have buttons that are used with action listeners as the input method.

  9. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Simple Calculator HELP

    How is the code executed? I don't see the main() method in any class to start the execution.

    That output was all from just entering a 9?
    If you don't understand my answer, don't ignore it, ask a question.

  10. #9
    Junior Member
    Join Date
    Apr 2014
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Simple Calculator HELP

    The code is executed in BlueJ. When you create a class in BlueJ, it allows you to open it without that-- I think. There really isn't much of a problem with the Calculator and the UserInterface classes. The buttons send the value into a basic array. When I run the getDisplayValue() method, I iterate though the Array, and the numbers go into a field in the calculator display.

  11. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Simple Calculator HELP

    Try debugging the code in the getDisplayValue() method by adding some println() statements that print out the values of all the variables that the method uses as it calculates the values.
    Use the Arrays class's toString() method to format the array for printing:
    System.out.println("an ID "+ java.util.Arrays.toString(theArrayName));
    If you don't understand my answer, don't ignore it, ask a question.

  12. #11
    Junior Member
    Join Date
    Apr 2014
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Simple Calculator HELP

    I have already debugged the code. The code is literally perfect until the final steps. However, when the index 0, the variable become a weird number. finalNumber becomes 41600409 and placeValue becomes 141600409.

  13. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Simple Calculator HELP

    I have already debugged the code.
    How, I don't see any println() statments that would show you what the code was doing.

    When you added the println() statements I suggested:
    When you enter the first number say an 8:
    What printed out for the contents of the array?
    What printed out for the value of finalNumber?

    What value should be shown in the text area?
    If you don't understand my answer, don't ignore it, ask a question.

  14. #13
    Junior Member
    Join Date
    Apr 2014
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Simple Calculator HELP

    Well, in BlueJ there is a built in debugger. And the thing is that when I press 8 I get the number -58993459 for the value of finalNumber, while 8 the number is located at [0] in the array.

  15. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Simple Calculator HELP

    When an 8 is entered, what should be shown in the textarea?
    Debug the steps in the getDisplayValue() method that compute the value of finalNumber.
    Print the value of finalNumber every time its value is changed and post it here.
    Should its value be 8?
    If you don't understand my answer, don't ignore it, ask a question.

  16. #15
    Junior Member
    Join Date
    Apr 2014
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Simple Calculator HELP

    0
    0
    0
    0
    0
    0
    0
    0
    0
    -589934592
    The final value shouldn't be that crazy number; it should be 8. This is a calculator, so I should be able to press the buttons and have them apear in the text field.

  17. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Simple Calculator HELP

    Also print these values:
    what's in finalNumber when the method starts executing?
    the value of placeValue every time it is changed inside the loop

    Press 2 instead of 8
    If you don't understand my answer, don't ignore it, ask a question.

  18. #17
    Junior Member
    Join Date
    Apr 2014
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Simple Calculator HELP

    finalNumber at start: 0.
    placeValue:
    1
    10
    100
    1000
    10000
    100000
    1000000
    10000000
    100000000
    1000000000

  19. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Simple Calculator HELP

    Can you see what the code is doing? It is ALWAYS multiplying the numbers 10 times ONCE for each slot in the array. Shouldn't it just use what has been entered?

    The reason the numbers go weird is that an int holds a max value of 2 billion. Larger numbers are truncated leaving whatever.

    Your debug print out needs both finalNumber and placeValue every time they are changed so you can see what is happening.

    What is the value of finalNumber when the second button is pressed?
    Continue debugging that method so you see what it is doing.

    I'm done for tonight. Back tomorrow.
    If you don't understand my answer, don't ignore it, ask a question.

  20. #19
    Junior Member
    Join Date
    Apr 2014
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Simple Calculator HELP

    Okay, thank you for you help. I will try and fix it from here.

Similar Threads

  1. Help with simple calculator
    By GMPoison in forum What's Wrong With My Code?
    Replies: 2
    Last Post: September 22nd, 2013, 01:29 PM
  2. Simple Calculator
    By Spanky13 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: February 25th, 2013, 05:33 PM
  3. [SOLVED] Simple calculator issue
    By ikocijan in forum What's Wrong With My Code?
    Replies: 5
    Last Post: June 20th, 2012, 02:43 AM
  4. Need help building a simple calculator
    By zigma in forum What's Wrong With My Code?
    Replies: 4
    Last Post: October 14th, 2011, 01:13 AM
  5. Simple Calculator
    By JKDSurfer in forum Loops & Control Statements
    Replies: 3
    Last Post: June 28th, 2011, 01:37 PM