+ Reply to Thread
Results 1 to 9 of 9

Thread: Source Code: Calculator App

  1. #1
    Blmaster is offline Learning Programmer
    Join Date
    Jul 2008
    Posts
    50
    Rep Power
    14

    Source Code: Calculator App

    Here is another little thing i was working on.
    Its just a Calculator Application that I though I should make to get the hang of Java. Of course i did have a bit of outside help with some commands.
    Here it is:

    [It might be better for you to see the code if you copy and paste into your own text editer because the comments are a bit off in this one.]
    Code:
    /*
    	Title: Calculator App
    	Created: August 7, 2008
    	Author: Blmaster
    	Comments:
    		Wanted to see if I could make it.
    	Changes:
    		1.9- Added Backspace function
    		1.8- fixed bug in 1.7 function. Intefered with equal sign
    		1.7- added function where you can change operator before clicking numbers
    		1.6- organized code (more compact)
    		1.5- added Clear, Clear Existing function
    		1.2- fixed bug in 1.1 function
    		1.1- added function to keep calculating without pressing enter
    		1.0- added basic operator functions
    		0.5- made layout of app
    */
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class Calculator implements ActionListener		{
    	private final double VERSION = 1.9;
    	//Initializes window, buttons, panels, textfield and other variables
    	JFrame window = new JFrame("Calculator " + VERSION);
    	JButton buttons[] = new JButton[20];
    	JPanel pnlBottom, pnlBackspace, pnlClear, pnlButtons;
    	JTextField txtDisplay;
    	String TempNum;
    	String Sign;
    	double FirstNum, SecondNum, Result;
    	boolean decimalUsed, Second, makeSecondTrue;
    	final int MAX_INPUT = 36;
    	
    	//constructor for Calculator
    	Calculator() {
    		//Window Properties
    		window.setSize(270, 186);
    		window.setLocation(530, 230);
    		window.setLayout(new BorderLayout());
    		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		window.setResizable(false);
    	
    		//Making Panels
    /*		pnlButtons holds all the Buttons Except for Backspace, CE, and C buttons
    		pnlClear holds CE and C Buttons
    		pnlBackspace holds the Backspace Button
    		pnlBottom holds all the other Panels so I can put them all at the bottom of the window			*/
    		pnlBottom = new JPanel();
    		pnlBackspace = new JPanel();
    		pnlClear = new JPanel();
    		pnlButtons = new JPanel();
    		
    		//Setting Layouts for the Panels
    		pnlBottom.setLayout(new BorderLayout());
    		pnlButtons.setLayout(new GridLayout(4, 4, 2, 2));
    		pnlClear.setLayout(new GridLayout(1, 2, 2, 2));
    		pnlBackspace.setLayout(new GridLayout(1, 2, 2, 2));
    		
    		//Text Field Properties
    		txtDisplay = new JTextField("0");
    		txtDisplay.setEditable(false);
    		txtDisplay.setHorizontalAlignment(JTextField.TRAILING);
    		txtDisplay.setBackground(Color.WHITE);
    		txtDisplay.setOpaque(true);
    		
    		//Making Buttons and adding to Panel Buttons
    		buttons[0] = new JButton("0");
    		buttons[10] = new JButton(".");
    		buttons[11] = new JButton("=");
    		buttons[12] = new JButton("/");
    		buttons[13] = new JButton("*");
    		buttons[14] = new JButton("-");
    		buttons[15] = new JButton("+");
    		for(int i=7; i<10; i++)	{
    			buttons[i] = new JButton(String.valueOf(i));
    			pnlButtons.add(buttons[i]);
    		}
    		pnlButtons.add(buttons[12]);
    		for(int i=4; i<7; i++)	{
    			buttons[i] = new JButton(String.valueOf(i));
    			pnlButtons.add(buttons[i]);
    		}
    		pnlButtons.add(buttons[13]);
    		for(int i=1; i<4; i++)	{
    			buttons[i] = new JButton(String.valueOf(i));
    			pnlButtons.add(buttons[i]);
    		}
    		pnlButtons.add(buttons[14]);
    		pnlButtons.add(buttons[0]);
    		pnlButtons.add(buttons[10]);
    		pnlButtons.add(buttons[11]);
    		pnlButtons.add(buttons[15]);
    		
    		//Creating Backspace Button and adding it to Backspace panel
    		buttons[16] = new JButton("BackSpace");
    		pnlBackspace.add(buttons[16]);
    		
    		//Creating Clear Buttons and adding it to Clear panel
    		buttons[17] = new JButton("CE");
    		buttons[18] = new JButton(" C ");
    		pnlClear.add(buttons[17]);
    		pnlClear.add(buttons[18]);
    		
          /*Adds Action Listener to every button 
    		and adds color to all the numbered buttons
    		plus the decimal and all the other buttons 
    		to red												*/
    		for(int i=0; i<19; i++)	{
    			buttons[i].addActionListener(this);
    			if(i<11)
    				buttons[i].setForeground(Color.blue);
    			else
    				buttons[i].setForeground(Color.red);
    		}
    		
    		//Adds Panels to window and shows window
    		pnlBottom.add(pnlBackspace, BorderLayout.WEST);
    		pnlBottom.add(pnlClear, BorderLayout.EAST);
    		pnlBottom.add(pnlButtons, BorderLayout.SOUTH);
    		window.add(txtDisplay, BorderLayout.NORTH);
    		window.add(pnlBottom, BorderLayout.SOUTH);
    		window.setVisible(true);
    		
    		//Sets Variables to Default
    		Reset();
    	}
    	
    	public void actionPerformed(ActionEvent click)	{
    		System.out.println("Action Performed");
    		//	Adding Digits to Screen
    		for(int i=0; i<10; i++)	{
    			if(click.getSource() == buttons[i])
    				addDigit(String.valueOf(i));
    		}
    		//	DECIMAL POINT
    		if(click.getSource() == buttons[10])	{
    			if(!decimalUsed)	{
    				addDigit(".");
    				decimalUsed = true;
    			}
    		}
    		//	EQUAL
    		if(click.getSource() == buttons[11])	{
    			Calculate("=");
    		}
    		//	DIVDIE
    		if(click.getSource() == buttons[12])	{
    			Calculate("/");
    		}
    		//	MULTIPLY
    		if(click.getSource() == buttons[13])	{
    			Calculate("*");
    		}
    		//	SUBTRACT
    		if(click.getSource() == buttons[14])	{
    			Calculate("-");
    		}
    		//	ADD
    		if(click.getSource() == buttons[15])	{
    			Calculate("+");
    		}
    		//	BACKSPACE
    		if(click.getSource() == buttons[16])	{
    			if(txtDisplay.getText().length() <= 1)	{
    				TempNum = "";
    				txtDisplay.setText("0");
    			}	else	{
    				TempNum = txtDisplay.getText().substring(0, txtDisplay.getText().length() - 1);
    				txtDisplay.setText(TempNum);
    			}
    		}
    		//	C
    		if(click.getSource() == buttons[17])	{
    			TempNum = "";
    			txtDisplay.setText("0");
    		}
    		//	CE
    		if(click.getSource() == buttons[18])	{
    			Reset();
    		}
    	}
    	
    /*	Adds digit to screen
    	If the text field contains a 0 and we click the button 0 it wont do anything	*/
    	public void addDigit(String digit)	{
    		if(txtDisplay.getText().equals("0") && digit.equals("0"))	{/*do nothing*/ } else {
    			if(txtDisplay.getText().length() < MAX_INPUT)	{
    				TempNum += digit;
    				txtDisplay.setText(TempNum);
    				if(makeSecondTrue)
    					Second = true;
    			}
    		}
    	}
    	
    /*	Calculates if /, *, -, +, or = sign is pressed 
    	Second and makeSecondTrue are here because
    	Second should only be true if a digit is pressed after the First Part	*/
    	public void Calculate(String operator)	{
    		decimalUsed = false;
    		if(operator.equals("="))	{
    			Result = Process();
    			Display(Result);
    			Second = false;
    			makeSecondTrue = false;
    		}	else {
    			if(Second)	{	/////////////////
    				Result = Process();			//
    				Display(Result);				//	Second Part
    				FirstNum = Result;			//
    			}	else {		/////////////////           ///////////////////
    				FirstNum = Double.parseDouble(txtDisplay.getText());		//First Part
    				makeSecondTrue = true;												//
    			}														////////////////////
    			Sign = operator;
    		}
    		TempNum = "";	
    	}
    	
    	
    /*	Makes the number in text field SecondNum 
    	Returns the result of whatever calculation the user has pressed ( / , * , - , + )	*/
    	public double Process()	{
    		SecondNum = Double.parseDouble(txtDisplay.getText());
    		System.out.println(SecondNum);
    		if(Sign.equals("*"))
    			return (FirstNum * SecondNum);
    		else if(Sign.equals("-"))
    			return (FirstNum - SecondNum);
    		else if(Sign.equals("+"))
    			return (FirstNum + SecondNum);
    		else if(Sign.equals("/"))	{
    			if(SecondNum == 0)	{
    				return -1.0; //if second number is 0 and it is a division operator, return -1
    								//	so when displayed, it gives a message, "Cannot Divide by Zero"
    			}	else
    				return (FirstNum / SecondNum);
    		}
    		else
    			return -2.0;	//anything other than (/, *, -, +) should return -2 so when displayed it gives error
    	}
    	
    	//Displays a double number unless if some errors are created 
    	public void Display(double num)	{
    		if(num == -1.0)
    			txtDisplay.setText("Cannot Divide by Zero!");
    		else if(num == -2.0)
    			txtDisplay.setText("Error!");
    		else
    			txtDisplay.setText(String.valueOf(num));
    	}
    	
    	//Resets everything to startup
    	public void Reset()	{
    		TempNum = "";
    		Sign = "0";
    		txtDisplay.setText("0");
    		FirstNum = 0.0; SecondNum = 0.0; Result = 0.0;
    		decimalUsed = false;
    		Second = false;
    		makeSecondTrue = false;
    	}
    	
    /*	Since you cant call a class (you can only call a method),
    	we have to make a instance of it. An example would be like,
    	you cant call a car so it magically appears in front of you,
    	but you can make a car. Something like that.
    	The "new" makes a new Calculator and pretty much calls
    	the code in the class and the class contructor.						 */	
    	public static void main(String[] args)	{
    		new Calculator();
    	}
    }

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Posts
    Many

     
  3. #2
    Join Date
    May 2008
    Location
    Hell
    Posts
    3,852
    Blog Entries
    4
    Rep Power
    49

    Re: Source Code: Calculator App

    Nostalgic, I feel like I have seen that thing somewhere I don't remember... Anyways good thing you made there I guess.

  4. #3
    Blmaster is offline Learning Programmer
    Join Date
    Jul 2008
    Posts
    50
    Rep Power
    14

    Calculator App 2.0 (Bug Fix)

    I think I know where you got it from... a swing tutorial, right? because I used it to know how they changed the color on the buttons. Other than that I did look at how they did the calculator but I didnt like it that much as they have it a bit complicated, i think atleast, so I made up my own! I might use it again to learn how to put in a menu bar up top.

    Anyways I have an update to the program:
    (fixed a bug that didn't let you change the operator sign after the first calculation)
    Code:
    /*
    	Title: Calculator App
    	Created: August 7, 2008
    	Author: Blmaster
    	Comments:
    		Wanted to see if I could make it.
    	Changes:
    		2.0- fixed another bug in 1.7. Couldnt do function 1.7 after first time.
    		1.9- Added Backspace function
    		1.8- fixed bug in 1.7 function. Intefered with equal sign
    		1.7- added function where you can change operator before clicking numbers
    		1.6- organized code (more compact)
    		1.5- added Clear, Clear Existing function
    		1.2- fixed bug in 1.1 function
    		1.1- added function to keep calculating without pressing enter
    		1.0- added basic operator functions
    		0.5- made layout of app
    */
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class Calculator implements ActionListener		{
    	private final double VERSION = 2.0;
    	//Initializes window, buttons, panels, textfield and other variables
    	JFrame window = new JFrame("Calculator " + VERSION);
    	JButton buttons[] = new JButton[20];
    	JPanel pnlBottom, pnlBackspace, pnlClear, pnlButtons;
    	JTextField txtDisplay;
    	String TempNum;
    	String Sign;
    	double FirstNum, SecondNum, Result;
    	boolean decimalUsed, Second, makeSecondTrue;
    	final int MAX_INPUT = 36;
    	
    	//constructor for Calculator
    	Calculator() {
    		//Window Properties
    		window.setSize(270, 186);
    		window.setLocation(530, 230);
    		window.setLayout(new BorderLayout());
    		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		window.setResizable(false);
    	
    		//Making Panels
    /*		pnlButtons holds all the Buttons Except for Backspace, CE, and C buttons
    		pnlClear holds CE and C Buttons
    		pnlBackspace holds the Backspace Button
    		pnlBottom holds all the other Panels so I can put them all at the bottom of the window			*/
    		pnlBottom = new JPanel();
    		pnlBackspace = new JPanel();
    		pnlClear = new JPanel();
    		pnlButtons = new JPanel();
    		
    		//Setting Layouts for the Panels
    		pnlBottom.setLayout(new BorderLayout());
    		pnlButtons.setLayout(new GridLayout(4, 4, 2, 2));
    		pnlClear.setLayout(new GridLayout(1, 2, 2, 2));
    		pnlBackspace.setLayout(new GridLayout(1, 2, 2, 2));
    		
    		//Text Field Properties
    		txtDisplay = new JTextField("0");
    		txtDisplay.setEditable(false);
    		txtDisplay.setHorizontalAlignment(JTextField.TRAILING);
    		txtDisplay.setBackground(Color.WHITE);
    		txtDisplay.setOpaque(true);
    		
    		//Making Buttons and adding to Panel Buttons
    		buttons[0] = new JButton("0");
    		buttons[10] = new JButton(".");
    		buttons[11] = new JButton("=");
    		buttons[12] = new JButton("/");
    		buttons[13] = new JButton("*");
    		buttons[14] = new JButton("-");
    		buttons[15] = new JButton("+");
    		for(int i=7; i<10; i++)	{
    			buttons[i] = new JButton(String.valueOf(i));
    			pnlButtons.add(buttons[i]);
    		}
    		pnlButtons.add(buttons[12]);
    		for(int i=4; i<7; i++)	{
    			buttons[i] = new JButton(String.valueOf(i));
    			pnlButtons.add(buttons[i]);
    		}
    		pnlButtons.add(buttons[13]);
    		for(int i=1; i<4; i++)	{
    			buttons[i] = new JButton(String.valueOf(i));
    			pnlButtons.add(buttons[i]);
    		}
    		pnlButtons.add(buttons[14]);
    		pnlButtons.add(buttons[0]);
    		pnlButtons.add(buttons[10]);
    		pnlButtons.add(buttons[11]);
    		pnlButtons.add(buttons[15]);
    		
    		//Creating Backspace Button and adding it to Backspace panel
    		buttons[16] = new JButton("BackSpace");
    		pnlBackspace.add(buttons[16]);
    		
    		//Creating Clear Buttons and adding it to Clear panel
    		buttons[17] = new JButton("CE");
    		buttons[18] = new JButton(" C ");
    		pnlClear.add(buttons[17]);
    		pnlClear.add(buttons[18]);
    		
          /*Adds Action Listener to every button 
    		and adds color to all the numbered buttons
    		plus the decimal and all the other buttons 
    		to red												*/
    		for(int i=0; i<19; i++)	{
    			buttons[i].addActionListener(this);
    			if(i<11)
    				buttons[i].setForeground(Color.blue);
    			else
    				buttons[i].setForeground(Color.red);
    		}
    		
    		//Adds Panels to window and shows window
    		pnlBottom.add(pnlBackspace, BorderLayout.WEST);
    		pnlBottom.add(pnlClear, BorderLayout.EAST);
    		pnlBottom.add(pnlButtons, BorderLayout.SOUTH);
    		window.add(txtDisplay, BorderLayout.NORTH);
    		window.add(pnlBottom, BorderLayout.SOUTH);
    		window.setVisible(true);
    		
    		//Sets Variables to Default
    		Reset();
    	}
    	
    	public void actionPerformed(ActionEvent click)	{
    		System.out.println("Action Performed");
    		//	Adding Digits to Screen
    		for(int i=0; i<10; i++)	{
    			if(click.getSource() == buttons[i])
    				addDigit(String.valueOf(i));
    		}
    		//	DECIMAL POINT
    		if(click.getSource() == buttons[10])	{
    			if(!decimalUsed)	{
    				addDigit(".");
    				decimalUsed = true;
    			}
    		}
    		//	EQUAL
    		if(click.getSource() == buttons[11])	{
    			Calculate("=");
    		}
    		//	DIVDIE
    		if(click.getSource() == buttons[12])	{
    			Calculate("/");
    		}
    		//	MULTIPLY
    		if(click.getSource() == buttons[13])	{
    			Calculate("*");
    		}
    		//	SUBTRACT
    		if(click.getSource() == buttons[14])	{
    			Calculate("-");
    		}
    		//	ADD
    		if(click.getSource() == buttons[15])	{
    			Calculate("+");
    		}
    		//	BACKSPACE
    		if(click.getSource() == buttons[16])	{
    			if(txtDisplay.getText().length() <= 1)	{
    				TempNum = "";
    				txtDisplay.setText("0");
    			}	else	{
    				TempNum = txtDisplay.getText().substring(0, txtDisplay.getText().length() - 1);
    				txtDisplay.setText(TempNum);
    			}
    		}
    		//	C
    		if(click.getSource() == buttons[17])	{
    			TempNum = "";
    			txtDisplay.setText("0");
    		}
    		//	CE
    		if(click.getSource() == buttons[18])	{
    			Reset();
    		}
    	}
    	
    /*	Adds digit to screen
    	If the text field contains a 0 and we click the button 0 it wont do anything	*/
    	public void addDigit(String digit)	{
    		if(txtDisplay.getText().equals("0") && digit.equals("0"))	{/*do nothing*/ } else {
    			if(txtDisplay.getText().length() < MAX_INPUT)	{
    				TempNum += digit;
    				txtDisplay.setText(TempNum);
    				if(makeSecondTrue)
    					Second = true;
    			}
    		}
    	}
    	
    /*	Calculates if /, *, -, +, or = sign is pressed 
    	Second and makeSecondTrue are here because
    	Second should only be true if a digit is pressed after the First Part	*/
    	public void Calculate(String operator)	{
    		decimalUsed = false;
    		if(operator.equals("="))	{
    			Result = Process();
    			Display(Result);
    			Second = false;
    			makeSecondTrue = false;
    		}	else {
    			if(Second)	{	/////////////////
    				Result = Process();			//
    				Display(Result);				//	Second Part
    				FirstNum = Result;			//
    				Second = false;				//
    			}	else {		/////////////////           ///////////////////
    				FirstNum = Double.parseDouble(txtDisplay.getText());		//First Part
    				makeSecondTrue = true;												//
    			}														////////////////////
    			Sign = operator;
    		}
    		TempNum = "";	
    	}
    	
    	
    /*	Makes the number in text field SecondNum 
    	Returns the result of whatever calculation the user has pressed ( / , * , - , + )	*/
    	public double Process()	{
    		SecondNum = Double.parseDouble(txtDisplay.getText());
    		System.out.println(SecondNum);
    		if(Sign.equals("*"))
    			return (FirstNum * SecondNum);
    		else if(Sign.equals("-"))
    			return (FirstNum - SecondNum);
    		else if(Sign.equals("+"))
    			return (FirstNum + SecondNum);
    		else if(Sign.equals("/"))	{
    			if(SecondNum == 0)	{
    				return -1.0; //if second number is 0 and it is a division operator, return -1
    								//	so when displayed, it gives a message, "Cannot Divide by Zero"
    			}	else
    				return (FirstNum / SecondNum);
    		}
    		else
    			return -2.0;	//anything other than (/, *, -, +) should return -2 so when displayed it gives error
    	}
    	
    	//Displays a double number unless if some errors are created 
    	public void Display(double num)	{
    		if(num == -1.0)
    			txtDisplay.setText("Cannot Divide by Zero!");
    		else if(num == -2.0)
    			txtDisplay.setText("Error!");
    		else
    			txtDisplay.setText(String.valueOf(num));
    	}
    	
    	//Resets everything to startup
    	public void Reset()	{
    		TempNum = "";
    		Sign = "0";
    		txtDisplay.setText("0");
    		FirstNum = 0.0; SecondNum = 0.0; Result = 0.0;
    		decimalUsed = false;
    		Second = false;
    		makeSecondTrue = false;
    	}
    	
    /*	Since you cant call a class (you can only call a method),
    	we have to make a instance of it. An example would be like,
    	you cant call a car so it magically appears in front of you,
    	but you can make a car. Something like that.
    	The "new" makes a new Calculator and pretty much calls
    	the code in the class and the class contructor.						 */	
    	public static void main(String[] args)	{
    		new Calculator();
    	}
    }

  5. #4
    Blmaster is offline Learning Programmer
    Join Date
    Jul 2008
    Posts
    50
    Rep Power
    14

    Re: Source Code: Calculator App

    Wow, i also forgot that i used the swing tutorial to learn how they did the layout and also how to do backspace function... sorry for reposting but I didnt want to forget to mention that. I mainly used it to learn how they did that layout... its pretty good.

  6. #5
    Blmaster is offline Learning Programmer
    Join Date
    Jul 2008
    Posts
    50
    Rep Power
    14

    Calculator 3.0

    Next Verison: Calculator Application 3.0!

    Here is the code:

    Code:
    /*
    	Title: Calculator App
    	Created: August 7, 2008
    	Author: Yadu Raghu
    	Comments:
    		Wanted to see if I could make it.
    	Changes:
    		See Bottom of Code ||
    		*******************\/
    */
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class Calculator implements ActionListener, ItemListener		{
    	private final double VERSION = 3.0;
    //Initializes window, buttons, panels, textfield and other variables
    	JFrame window = new JFrame("Calculator " + VERSION);
    	JMenuBar Menu = new JMenuBar();
    	JMenu mnuProgram, mnuView, mnuHelp;
    	JMenuItem mnuReset, mnuExit, mnuAbout;
    	JCheckBoxMenuItem mnuShowCalc;
    	JPanel pnlBottom, pnlBackspace, pnlClear, pnlButtons, pnlCalculation;
    	JLabel lblFirst, lblOperator, lblSecond, lblEqual, lblResult;
    	JTextField txtDisplay;
    	JButton buttons[] = new JButton[20];
    	
    	final short MAX_INPUT = 30;
    	String TempNum;
    	String Sign;
    	double FirstNum, SecondNum, Result;
    	boolean decimalUsed, Second, makeSecondTrue, secondNum;
    	
    //constructor for Calculator
    	Calculator() {
    		//Window Properties
    		window.setSize(270, 210);
    		window.setLocation(530, 230);
    		window.setLayout(new BorderLayout());
    		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		window.setResizable(false);
    		
    //Making the Menu and Menu Items and adding action listener
    		mnuProgram = new JMenu("Program");
    		mnuView = new JMenu("View");
    		mnuHelp = new JMenu("Help");
    		Menu.add(mnuProgram);         
    		Menu.add(mnuView);
    		Menu.add(mnuHelp);
    		mnuReset = new JMenuItem("Reset");
    		mnuExit = new JMenuItem("Exit");
    		mnuProgram.add(mnuReset);
    		mnuProgram.add(mnuExit);
    		mnuShowCalc = new JCheckBoxMenuItem("Show Calculations");
    		mnuView.add(mnuShowCalc);
    		mnuAbout = new JMenuItem("About Calculator");
    		mnuHelp.add(mnuAbout);
    		mnuReset.addActionListener(this);
    		mnuExit.addActionListener(this);
    		mnuShowCalc.addItemListener(this);
    		mnuAbout.addActionListener(this);
    		
    		//Making Panels
    /*		pnlButtons holds all the Buttons Except for Backspace, CE, and C buttons
    		pnlClear holds CE and C Buttons
    		pnlBackspace holds the Backspace Button
    		pnlBottom holds all the other Panels so I can put them all at the bottom of the window
    		pnlCalculations holds all the Labels for the Show Calcualtions function			*/
    		pnlBottom = new JPanel();
    		pnlBackspace = new JPanel();
    		pnlClear = new JPanel();
    		pnlButtons = new JPanel();
    		pnlCalculation = new JPanel();
    		
    		//Setting Layouts for the Panels and other Properties
    		pnlBottom.setLayout(new BorderLayout());
    		pnlButtons.setLayout(new GridLayout(4, 4, 2, 2));
    		pnlClear.setLayout(new GridLayout(1, 2, 2, 2));
    		pnlBackspace.setLayout(new GridLayout(1, 2, 2, 2));
    		pnlCalculation.setLayout(new FlowLayout(FlowLayout.CENTER));
    		pnlBottom.setBackground(new Color(200, 200, 200));
    		
    		//Making Labels and adding them to pnlCalculation Panel.
    		lblFirst = new JLabel("0");
    		lblOperator = new JLabel("?");
    		lblSecond = new JLabel("0");
    		lblEqual = new JLabel("=");
    		lblResult = new JLabel("0");
    		pnlCalculation.add(lblFirst);
    		pnlCalculation.add(lblOperator);
    		pnlCalculation.add(lblSecond);
    		pnlCalculation.add(lblEqual);
    		pnlCalculation.add(lblResult);
    		
    		//Text Field Properties
    		txtDisplay = new JTextField("0");
    		txtDisplay.setEditable(false);
    		txtDisplay.setHorizontalAlignment(JTextField.TRAILING);
    		txtDisplay.setBackground(Color.WHITE);
    		txtDisplay.setOpaque(true);
    		
    		//Making Buttons and adding to Panel Buttons
    		buttons[0] = new JButton("0");
    		buttons[10] = new JButton(".");
    		buttons[11] = new JButton("=");
    		buttons[12] = new JButton("/");
    		buttons[13] = new JButton("*");
    		buttons[14] = new JButton("-");
    		buttons[15] = new JButton("+");
    		for(int i=7; i<10; i++)	{
    			buttons[i] = new JButton(String.valueOf(i));
    			pnlButtons.add(buttons[i]);
    		}
    		pnlButtons.add(buttons[12]);
    		for(int i=4; i<7; i++)	{
    			buttons[i] = new JButton(String.valueOf(i));
    			pnlButtons.add(buttons[i]);
    		}
    		pnlButtons.add(buttons[13]);
    		for(int i=1; i<4; i++)	{
    			buttons[i] = new JButton(String.valueOf(i));
    			pnlButtons.add(buttons[i]);
    		}
    		pnlButtons.add(buttons[14]);
    		pnlButtons.add(buttons[0]);
    		pnlButtons.add(buttons[10]);
    		pnlButtons.add(buttons[11]);
    		pnlButtons.add(buttons[15]);
    		
    		//Creating Backspace Button and adding it to Backspace panel
    		buttons[16] = new JButton("BackSpace");
    		pnlBackspace.add(buttons[16]);
    		
    		//Creating Clear Buttons and adding it to Clear panel
    		buttons[17] = new JButton("CE");
    		buttons[18] = new JButton(" C ");
    		pnlClear.add(buttons[17]);
    		pnlClear.add(buttons[18]);
    		
          /*Adds Action Listener to every button 
    		and adds color to all the numbered buttons
    		plus the decimal and all the other buttons 
    		to red												*/
    		for(int i=0; i<19; i++)	{
    			buttons[i].addActionListener(this);
    			if(i<11)
    				buttons[i].setForeground(Color.blue);
    			else
    				buttons[i].setForeground(Color.red);
    		}
    		
    		//Adds Panels to window and shows window
    		pnlBottom.add(txtDisplay, BorderLayout.NORTH);
    		pnlBottom.add(pnlBackspace, BorderLayout.WEST);
    		pnlBottom.add(pnlClear, BorderLayout.EAST);
    		pnlBottom.add(pnlButtons, BorderLayout.SOUTH);
    		window.add(Menu, BorderLayout.NORTH);
    		window.add(pnlCalculation);
    		window.add(pnlBottom, BorderLayout.SOUTH);
    		window.setVisible(true);
    		
    		//Sets Variables to Default
    		Reset();
    	}
    	
    	public void actionPerformed(ActionEvent click)	{
    		//	Adding Digits to Screen
    		for(int i=0; i<10; i++)	{
    			if(click.getSource() == buttons[i])
    				addDigit(String.valueOf(i));
    		}
    		//	DECIMAL POINT
    		if(click.getSource() == buttons[10])	{
    			if(!decimalUsed)	{
    				addDigit(".");
    				decimalUsed = true;
    			}
    		}
    		//	EQUAL
    		if(click.getSource() == buttons[11])	{
    			Calculate("=");
    		}
    		//	DIVDIE
    		if(click.getSource() == buttons[12])	{
    			Calculate("/");
    		}
    		//	MULTIPLY
    		if(click.getSource() == buttons[13])	{
    			Calculate("*");
    		}
    		//	SUBTRACT
    		if(click.getSource() == buttons[14])	{
    			Calculate("-");
    		}
    		//	ADD
    		if(click.getSource() == buttons[15])	{
    			Calculate("+");
    		}
    		//	BACKSPACE
    		if(click.getSource() == buttons[16])	{
    			if(txtDisplay.getText().length() <= 1)	{
    				TempNum = "";
    				txtDisplay.setText("0");
    				if(secondNum)
    					lblSecond.setText("0");
    				else
    					lblFirst.setText("0");
    			}	else	{
    				TempNum = txtDisplay.getText().substring(0, txtDisplay.getText().length() - 1);
    				txtDisplay.setText(TempNum);
    				if(secondNum)
    					lblSecond.setText(TempNum);
    				else
    					lblFirst.setText(TempNum);
    			}
    		}
    		//	C
    		if(click.getSource() == buttons[17])	{
    			TempNum = "";
    			txtDisplay.setText("0");
    			checkCalculations();
    		}
    		//	CE
    		if(click.getSource() == buttons[18])	{
    			Reset();
    		}
    		// Program -> Reset
    		if(click.getSource() == mnuReset)	{
    			Reset();
    			window.setSize(270, 210);
    			mnuShowCalc.setState(false);
    			JOptionPane.showMessageDialog(null, "Reset!\nEverthing is back to default." 
    			, "Reset", JOptionPane.INFORMATION_MESSAGE);
    		}
    		// Program -> Exit
    		if(click.getSource() == mnuExit)	{
    			System.exit(0);
    		}
    		// Help -> About
    		if(click.getSource() == mnuAbout)	{
    			JOptionPane.showMessageDialog(null, "Calcualtor " + VERSION + 
    			"\nCreated by: Blmaster" + "\nCreated: August 7. 2008"
    			,"About Calculator", JOptionPane.INFORMATION_MESSAGE);
    		}
    	}
    
    /*	If the Menu Checkbox is clicked it will make the pnlCalculation visible and the window
    	bigger so the user can see it too. if it is unseleceted it will go back to normal			*/
    	public void itemStateChanged(ItemEvent click)	{
    		if(click.getSource() == mnuShowCalc)	{
    			if(click.getStateChange() == ItemEvent.SELECTED)	{
    				window.setSize(270, 235);
    				pnlCalculation.setVisible(true);
    			}	else {
    				window.setSize(270, 210);
    				pnlCalculation.setVisible(false);
    			}
    		}
    	}
    	
    	
    /*	Adds digit to screen
    	If the text field contains a 0 and we click the button 0 it wont do anything	*/
    	public void addDigit(String digit)	{
    		if(txtDisplay.getText().equals("0") && digit.equals("0"))	{/*do nothing*/ } else {
    			if(TempNum.length() < MAX_INPUT)	{
    				TempNum += digit;
    				txtDisplay.setText(TempNum);
    				if(makeSecondTrue)
    					Second = true;
    				checkCalculations();
    			}
    		}
    	}
    	
    /*	Calculates if /, *, -, +, or = sign is pressed 
    	Second and makeSecondTrue are here because
    	Second should only be true if a digit is pressed after the First Part	*/
    	public void Calculate(String operator)	{
    		decimalUsed = false;
    		secondNum = true;
    		if(operator.equals("="))	{
    			Result = Process();
    			Display(Result);
    			lblResult.setText(String.valueOf(Result));
    			Second = false;
    			makeSecondTrue = false;
    			secondNum = false;
    		}	else {
    			if(Second)	{	/////////////////
    				Result = Process();			//
    				Display(Result);				//	Second Part
    				FirstNum = Result;			//
    				lblFirst.setText(String.valueOf(FirstNum));
    				Second = false;				//
    			}	else {		/////////////////           ///////////////////
    				FirstNum = Double.parseDouble(txtDisplay.getText());		//First Part
    				lblFirst.setText(String.valueOf(FirstNum));					//
    				makeSecondTrue = true;												//
    			}														////////////////////
    			Sign = operator;
    		}
    		if(operator != "=")
    			lblOperator.setText(operator);
    		TempNum = "";	
    	}
    	
    	
    /*	Makes the number in text field SecondNum 
    	Returns the result of whatever calculation the user has pressed ( / , * , - , + )	*/
    	public double Process()	{
    		SecondNum = Double.parseDouble(txtDisplay.getText());
    		lblSecond.setText(String.valueOf(SecondNum));
    		if(Sign.equals("*"))
    			return (FirstNum * SecondNum);
    		else if(Sign.equals("-"))
    			return (FirstNum - SecondNum);
    		else if(Sign.equals("+"))
    			return (FirstNum + SecondNum);
    		else if(Sign.equals("/"))	{
    			if(SecondNum == 0)	{
    				return -.083; //if second number is 0 and it is a division operator, return -.083
    								//	s`o when displayed, it gives a message, "Cannot Divide by Zero"
    			}	else
    				return (FirstNum / SecondNum);
    		}
    		else
    			return -.084;	//anything other than (/, *, -, +) should return -.084 so when displayed it gives error
    	}
    	
    	//Displays a double number unless if some errors are created 
    	public void Display(double num)	{
    		if(num == -.083)
    			txtDisplay.setText("Cannot Divide by Zero!");
    		else if(num == -.084)
    			txtDisplay.setText("Error!");
    		else
    			txtDisplay.setText(String.valueOf(num));
    	}
    	
    /*	Checks the labels in pnlCalulation to the correct number corresponding with 
    	whatever user types in.																					*/
    	public void checkCalculations()	{
    		if(secondNum)	{
    			lblSecond.setText(TempNum);
    			if(TempNum == "")
    				lblSecond.setText("0");
    		} else {
    			lblFirst.setText(TempNum);
    			if(TempNum == "")
    				lblFirst.setText("0");
    			lblOperator.setText("?");
    			lblSecond.setText("0");
    			lblResult.setText("0");
    		}
    	}
    	
    	//Resets everything to startup
    	public void Reset()	{
    		TempNum = "";
    		Sign = "0";
    		txtDisplay.setText("0");
    		lblFirst.setText("0");
    		lblOperator.setText("?");
    		lblSecond.setText("0");
    		lblEqual.setText("=");
    		lblResult.setText("0");
    		FirstNum = 0.0; SecondNum = 0.0; Result = 0.0;
    		decimalUsed = false;
    		Second = false;
    		makeSecondTrue = false;
    		secondNum = false;
    	}
    	
    /*	Since you cant call a class (you can only call a method),
    	we have to make a instance of it. An example would be like,
    	you cant call a car so it magically appears in front of you,
    	but you can make a car. Something like that.
    	The "new" makes a new Calculator and pretty much calls
    	the code in the class contructor. 										 */	
    	public static void main(String[] args)	{
    		new Calculator();
    	}
    }
    
    /*
    Version Changes:
    	3.0- added menu bar with function Reset, Exit, show Calculation, About Calculator.
    	2.7-2.8: fixed bugs in 2.6 function
    	2.6- added new function show Calculation 
    	2.5- added menu bar.
    	2.2- fixed bug in MAX_INPUT
    	2.1- improved the error system. (Need to find another way for that though.)
    	2.0- fixed another bug in 1.7. Couldnt change the operator sign after the first calculation.
    	1.9- Added Backspace function.
    	1.8- fixed bug in 1.7 function. Intefered with equal sign.
    	1.7- added function where you can keep changing the operator sign if you hit another one by mistake.
    	1.6- reorganized code. Made methods that take up common tasks and made code more compact.
    	1.5- added the Clear and Clear Existing buttons.
    	1.2- fixed a bug in 1.1 function. It wasnt working properly after the first time you do it. Works perfectly now.
    	1.1- added function that lets you keep calculating without hitting the equal button. Ex- 2*5*2+3/5
    	1.0- added basic (/, *, -, +) operator functions.
    	0.5- made basic layout of the application.
    */

  7. #6
    Blmaster is offline Learning Programmer
    Join Date
    Jul 2008
    Posts
    50
    Rep Power
    14

    Calculator 4.0

    Version 4.0 (I believe it is pretty much bug free)

    Here is the code:
    (Copy and paste into whatever you use to compile your java stuff to see the code better)
    Code:
    /*
    	Title: Calculator App
    	Created: August 7, 2008
    	Author: Blmaster
    	Comments:
    		Wanted to see if I could make it.
    		Last Edited: August 20, 2008
    	Changes:
    		See Bottom of Code ||
    		*******************\/
    */
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class Calculator implements ActionListener, ItemListener, KeyListener		{
    	private final String VERSION = "4.0";
    //Initializes window, buttons, panels, textfield and other variables
    	JFrame window = new JFrame("Calculator " + VERSION);
    	JMenuBar Menu = new JMenuBar();
    	JMenu mnuProgram, mnuView, mnuHelp;
    	JMenuItem mnuReset, mnuExit, mnuAbout;
    	JCheckBoxMenuItem mnuShowCalc;
    	JPanel pnlBottom, pnlBackspace, pnlClear, pnlButtons, pnlCalculation;
    	JLabel lblFirst, lblOperator, lblSecond, lblEqual, lblResult;
    	JTextField txtDisplay;
    	JButton buttons[] = new JButton[23];
    	
    	final short MAX_INPUT = 30;
    	final float DIVIDE_ZERO_ERROR = (float)-.04060802;
    	final float ERROR = (float)-.04060801;
    	String tempNum;
    	String sign;
    	String Label;
    	String R;
    	String tempString;
    	double number1, number2, result;
    	boolean decimalUsed, secondNum, makeSecondTrue, lblSecondNum, secondEqual, error;
    //constructor for Calculator class
    	Calculator() {
    		//Window Properties
    		window.setSize(306, 210);
    		window.setLocation(470, 290);
    		window.setLayout(new BorderLayout());
    		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		window.setResizable(false);
    		
    //Making the Menu and Menu Items and adding action listener/item listener
    		mnuProgram = new JMenu("Program");
    		mnuView = new JMenu("View");
    		mnuHelp = new JMenu("Help");
    		Menu.add(mnuProgram);         
    		Menu.add(mnuView);
    		Menu.add(mnuHelp);
    		mnuReset = new JMenuItem("Reset");
    		mnuExit = new JMenuItem("Exit");
    		mnuShowCalc = new JCheckBoxMenuItem("Show Calculations");
    		mnuAbout = new JMenuItem("About Calculator");
    		mnuProgram.add(mnuReset);
    		mnuProgram.add(mnuExit);
    		mnuView.add(mnuShowCalc);
    		mnuHelp.add(mnuAbout);
    		mnuReset.addActionListener(this);
    		mnuExit.addActionListener(this);
    		mnuShowCalc.addItemListener(this);
    		mnuAbout.addActionListener(this);
    		
    		//Making Panels
    /*		pnlButtons holds all the Buttons Except for Backspace, CE, and C buttons
    		pnlClear holds CE and C Buttons
    		pnlBackspace holds the Backspace Button
    		pnlBottom holds all the other Panels so I can put them all at the bottom of the window
    		pnlCalculations holds all the Labels for the Show Calcualtions function			*/
    		pnlBottom = new JPanel();
    		pnlBackspace = new JPanel();
    		pnlClear = new JPanel();
    		pnlButtons = new JPanel();
    		pnlCalculation = new JPanel();
    		
    		//Setting Layouts for the Panels and other Properties
    		pnlBottom.setLayout(new BorderLayout());
    		pnlButtons.setLayout(new GridLayout(4, 5, 2, 2));
    		pnlClear.setLayout(new GridLayout(1, 2, 2, 2));
    		pnlBackspace.setLayout(new GridLayout(1, 2, 2, 2));
    		pnlCalculation.setLayout(new FlowLayout(FlowLayout.CENTER));
    		pnlBottom.setBackground(new Color(200, 200, 200));
    		
    		//Making Labels and adding them to pnlCalculation Panel.
    		lblFirst = new JLabel();
    		lblOperator = new JLabel();
    		lblSecond = new JLabel();
    		lblEqual = new JLabel();
    		lblResult = new JLabel();
    		pnlCalculation.add(lblFirst);
    		pnlCalculation.add(lblOperator);
    		pnlCalculation.add(lblSecond);
    		pnlCalculation.add(lblEqual);
    		pnlCalculation.add(lblResult);
    		
    		//Text Field Properties
    		txtDisplay = new JTextField("0");
    		txtDisplay.setEditable(false);
    		txtDisplay.setHorizontalAlignment(JTextField.TRAILING);
    		txtDisplay.setBackground(Color.WHITE);
    		txtDisplay.setOpaque(true);
    		txtDisplay.addKeyListener(this);
    		
    		//Making Buttons and adding to Panel Buttons
    		buttons[0] = new JButton("0");
    		buttons[10] = new JButton(".");
    		buttons[11] = new JButton("=");
    		buttons[12] = new JButton("/");
    		buttons[13] = new JButton("*");
    		buttons[14] = new JButton("-");
    		buttons[15] = new JButton("+");
    		buttons[16] = new JButton("sqrt");
    		buttons[17] = new JButton("%");
    		buttons[18] = new JButton("1/x");
    		buttons[19] = new JButton("+/-");
    		for(int i=7; i<10; i++)	{
    			buttons[i] = new JButton(String.valueOf(i));
    			pnlButtons.add(buttons[i]);
    		}
    		pnlButtons.add(buttons[12]);
    		pnlButtons.add(buttons[16]);
    		for(int i=4; i<7; i++)	{
    			buttons[i] = new JButton(String.valueOf(i));
    			pnlButtons.add(buttons[i]);
    		}
    		pnlButtons.add(buttons[13]);
    		pnlButtons.add(buttons[17]);
    		for(int i=1; i<4; i++)	{
    			buttons[i] = new JButton(String.valueOf(i));
    			pnlButtons.add(buttons[i]);
    		}
    		pnlButtons.add(buttons[14]);
    		pnlButtons.add(buttons[18]);
    		pnlButtons.add(buttons[0]);
    		pnlButtons.add(buttons[10]);
    		pnlButtons.add(buttons[11]);
    		pnlButtons.add(buttons[15]);
    		pnlButtons.add(buttons[19]);
    		
    		//Creating Backspace Button and adding it to Backspace panel
    		buttons[20] = new JButton("BackSpace");
    		pnlBackspace.add(buttons[20]);
    		
    		//Creating Clear Buttons and adding it to Clear panel
    		buttons[21] = new JButton("CE");
    		buttons[22] = new JButton(" C ");
    		pnlClear.add(buttons[21]);
    		pnlClear.add(buttons[22]);
    		
          /*Adds Action Listener to every button 
    		and adds color to all the numbered buttons
    		plus the decimal and all the other buttons 
    		to red												*/
    		for(int i=0; i<buttons.length; i++)	{
    			buttons[i].addActionListener(this);
    			if(i<11 || (i>15 && i<20))
    				buttons[i].setForeground(Color.blue);
    			else
    				buttons[i].setForeground(Color.red);
    		}
    		
    		//Adds Panels to window and shows window
    		pnlBottom.add(txtDisplay, BorderLayout.NORTH);
    		pnlBottom.add(pnlBackspace, BorderLayout.WEST);
    		pnlBottom.add(pnlClear, BorderLayout.EAST);
    		pnlBottom.add(pnlButtons, BorderLayout.SOUTH);
    		window.add(Menu, BorderLayout.NORTH);
    		window.add(pnlCalculation);
    		window.add(pnlBottom, BorderLayout.SOUTH);
    		window.setVisible(true);
    		pnlCalculation.setVisible(false);
    		
    		//Clears the screen. sets Variables to default.
    		Clear();
    	}
    	
    	public void actionPerformed(ActionEvent click)	{
    		//	Adding Digits to Screen
    		for(int i=0; i<10; i++)	{
    			if(click.getSource() == buttons[i])
    				addDigit(String.valueOf(i));
    		}
    		//	Adding Decimal Point to Screen
    		if(click.getSource() == buttons[10])	{
    			if(!decimalUsed)	{
    				addDigit(".");
    				decimalUsed = true;
    			}
    		}
    		for(int i=11; i<buttons.length; i++)	{
    			if(click.getSource() == buttons[i])	{
    				switch(i)	{
    					case 11:
    						Calculate("=");// EQUAL
    						break;
    					case 12:
    						Calculate("/");//	DIVDIE
    						break;
    					case 13:
    						Calculate("*");//	MULTIPLY
    						break;
    					case 14:
    						Calculate("-");//	SUBTRACT
    						break;
    					case 15:
    						Calculate("+");//	ADD
    						break;
    					case 16://	SQUARE ROOT
    						sqrt();
    						break;
    					case 17://	%
    						percent();
    						break;
    					case 18://	1/x
    						divideByX();
    						break;
    					case 19://	+/-
    						signChange();
    						break;
    					case 20://	BACKSPACE
    						Backspace();
    						break;
    					case 21://	CE
    						ClearExisting();
    						break;
    					case 22://	C
    						Clear();
    						break;
    				}
    			}
    		}
    		if(!(buttons[11] == click.getSource()))
    			secondEqual = false;
    		// Program -> Reset
    		if(click.getSource() == mnuReset)	{
    			Clear();
    			window.setSize(306, 210);
    			pnlCalculation.setVisible(false);
    			mnuShowCalc.setState(false);
    			JOptionPane.showMessageDialog(null, "Reset!\nEverthing is back to default." 
    			, "Reset", JOptionPane.INFORMATION_MESSAGE);
    		}
    		// Program -> Exit
    		if(click.getSource() == mnuExit)	{
    			System.exit(0);
    		}
    		// Help -> About
    		if(click.getSource() == mnuAbout)	{
    			showAboutDialog();
    		}
    		txtDisplay.requestFocus();
    	}
    
    
    /*	If the Menu Checkbox is clicked it will make the pnlCalculation visible and the window
    	bigger so the user can see it too. if it is unseleceted it will go back to normal			*/
    	public void itemStateChanged(ItemEvent click)	{
    		if(click.getSource() == mnuShowCalc)	{
    			if(click.getStateChange() == ItemEvent.SELECTED)	{
    				window.setSize(306, 235);
    				pnlCalculation.setVisible(true);
    			}	else {
    				window.setSize(306, 210);
    				pnlCalculation.setVisible(false);
    			}
    		}
    	}
    	
    	public void keyPressed(KeyEvent e)	{
    		int key = e.getKeyChar();
    		if(!(key == KeyEvent.VK_ENTER))
    			secondEqual = false;
    		switch(key)	{
    			case KeyEvent.VK_0:
    				addDigit("0");
    				break;
    			case KeyEvent.VK_1:
    				addDigit("1");
    				break;
    			case KeyEvent.VK_2:
    				addDigit("2");
    				break;
    			case KeyEvent.VK_3:
    				addDigit("3");
    				break;
    			case KeyEvent.VK_4:
    				addDigit("4");
    				break;
    			case KeyEvent.VK_5:
    				addDigit("5");
    				break;
    			case KeyEvent.VK_6:
    				addDigit("6");
    				break;
    			case KeyEvent.VK_7:
    				addDigit("7");
    				break;
    			case KeyEvent.VK_8:
    				addDigit("8");
    				break;
    			case KeyEvent.VK_9:
    				addDigit("9");
    				break;
    			case KeyEvent.VK_PERIOD:
    				if(!decimalUsed)	{
    					addDigit(".");
    					decimalUsed = true;
    				}
    				break;
    			case KeyEvent.VK_ENTER:
    				Calculate("=");
    				break;
    			case KeyEvent.VK_SLASH:
    				Calculate("/");
    				break;
    			case 42:
    				Calculate("*");
    				break;
    			case KeyEvent.VK_MINUS:
    				Calculate("-");
    				break;
    			case 43:
    				Calculate("+");
    				break;
    			case KeyEvent.VK_BACK_SPACE:
    				Backspace();
    				break;
    			case KeyEvent.VK_ESCAPE:
    				Clear();
    				break;
    			case KeyEvent.VK_DELETE:
    				ClearExisting();
    				break;
    		}
    	}
    	public void keyTyped(KeyEvent e)	{}
    	public void keyReleased(KeyEvent e)	{}
    	
    	
    
    
    
    
    	
    /*********************************************************************************************************************************	
    	NON-LISTENER METHODS
    /*********************************************************************************************************************************/
    	
    	
    /*	adds Digit to screen
    	But if TempNum is empty and the button we click is 0 then just set the display box to 0	*/
    	public void addDigit(String digit)	{
    		if(!error)	{
    			if(tempNum.equals("") && digit.equals("0"))	{
    				txtDisplay.setText("0");
    					tempNum = "";
    				if(lblSecondNum)
    					lblSecond.setText("0");
    				else	{
    					lblFirst.setText("0");
    					lblSecond.setText("_");
    					lblResult.setText("_");
    				}
    			}	else if(tempNum.length() < MAX_INPUT)	{
    				tempNum += digit;
    				if(tempNum.charAt(0) == '.')
    					tempNum = "0" + tempNum;
    				txtDisplay.setText(tempNum);
    				if(makeSecondTrue)
    					secondNum = true;
    				checkLabels();
    			}
    			secondEqual = false;
    		}
    	}
    	
    /*	Calculates if /, *, -, +, or = sign is pressed 
    	Second and makeSecondTrue are here because
    	Second should only be true if a digit is pressed after the First Part	*/
    	public void Calculate(String operator)	{
    		if(!error)	{
    			decimalUsed = false;
    			if(operator.equals("="))	{
    				if(secondEqual)	{	///////////
    					number1 = result;				//
    					result = Process();			//Equal Sign Pressed Twice or more
    					Display(result);				//
    				}	else	{				///////////			////////////////////
    					number2 = Double.parseDouble(txtDisplay.getText());	//
    					setSecondLabel();													//
    					result = Process();												//Equal Sign Pressed Once
    					Display(result);													//
    					number1 = result;													//
    					secondEqual = true;												//
    				}													////////////////////
    				secondNum = false;
    				makeSecondTrue = false;
    				lblSecondNum = false;
    			}	else {
    				if(secondNum)	{	/////////////////
    					number2 = Double.parseDouble(txtDisplay.getText());
    					setSecondLabel();					//
    					result = Process();				//
    					Display(result);					//Second Part
    					number1 = result;					//
    					lblSecond.setText("_");			//
    					lblResult.setText("_");			//
    					lblOperator.setText("?");		//
    					setFirstLabel(String.valueOf(result));
    					secondNum = false;				//
    				}	else {			/////////////////        ///////////////////
    					number1 = Double.parseDouble(txtDisplay.getText());		//
    					makeSecondTrue = true;												//
    					setFirstLabel();														//
    					lblSecond.setText("_");												//First Part
    					lblResult.setText("_");												//	
    					lblOperator.setText("?");											//
    					lblSecondNum = true;													//
    				}														////////////////////
    				sign = operator;	
    				secondEqual = false;
    			}
    			lblOperator.setText(sign);
    
    			tempNum = "";
    		}
    	}
    	
    /*	Makes the number in text field SecondNum 
    	Returns the result of whatever calculation the user has pressed ( / , * , - , + )	*/
    	public double Process()	{
    		if(sign.equals("*"))
    			return (number1 * number2);
    		else if(sign.equals("-"))
    			return (number1 - number2);
    		else if(sign.equals("+"))
    			return (number1 + number2);
    		else if(sign.equals("/"))	{
    			if(number2 == 0)
    				return DIVIDE_ZERO_ERROR; //if second number is 0 and it is a division operator, return DIVIDE_ZERO_ERROR
    										//	so when displayed, it gives a message, "Cannot Divide by Zero"
    			else
    				return (number1 / number2);
    		}
    		else
    			return ERROR;	//anything other than (/, *, -, +) should return ERROR so when displayed it gives error
    	}
    	
    	//Displays a double number unless if some errors are created 
    	public void Display(double num)	{
    		if(num == DIVIDE_ZERO_ERROR)	{
    			R = "Cannot Divide by Zero!";
    			error = true;
    		}
    		else if(num == ERROR)	{
    			R = "Invalid Input for Function!";
    			error = true;
    		}
    		else	{
    			R = String.valueOf(num);
    			if((R.charAt((R.length()) -1) == '0') && (R.charAt((R.length()) -2) == '.'))
    			R = R.substring(0, R.length() - 2);
    		}
    		txtDisplay.setText(R);
    		lblResult.setText(R);
    		setFirstLabel();
    	}
    	
    	//Square Root function. (sqrt)
    	public void sqrt()	{
    		if(!error)	{
    			tempString = txtDisplay.getText();
    			try {result = Math.sqrt(Double.parseDouble(tempString));} catch(Exception e) {result = ERROR;}
    			if(tempString.indexOf("-") == 0)
    				result = ERROR;
    			lblSecond.setText("sqrt( " + tempString + " )");
    			Display(result);
    			lblFirst.setText("");
    			lblOperator.setText("");
    			secondNum = false;
    			makeSecondTrue = false;
    			lblSecondNum = false;
    			tempNum = "";
    		}
    	}
    	
    	//converts number to percent (%)
    	public void percent()	{
    		if(!error)	{
    			tempString = txtDisplay.getText();
    			try {result = (Double.parseDouble(tempString) / 100);} catch(Exception e) {result = ERROR;}
    			Display(result);
    			setFirstLabel(tempString);
    			lblOperator.setText("/");
    			setSecondLabel("100");
    			secondNum = false;
    			makeSecondTrue = false;
    			lblSecondNum = false;
    			tempNum = "";
    		}
    	}
    	
    	//1 Divide by X function (1/x)
    	public void divideByX()	{
    		if(!error)	{
    			tempString = txtDisplay.getText();
    			if(tempString.equals("0"))
    				result = DIVIDE_ZERO_ERROR;
    			else
    				try {result = 1 / Double.parseDouble(tempString);} catch(Exception e) {result = ERROR;}
    			setSecondLabel(tempString);
    			Display(result);
    			setFirstLabel("1");
    			lblOperator.setText("/");
    			secondNum = false;
    			makeSecondTrue = false;
    			lblSecondNum = false;
    			tempNum = "";
    		}
    	}
    	
    	//Makes it negative if positive and vice versa
    	public void signChange()	{
    		if(!error)	{
    			tempString = txtDisplay.getText();
    			if(tempString.equals("0"))	
    			{
    				/* Do Nothing*/
    			}	else	{
    				if(tempString.charAt(0) == '-')
    					tempNum = tempNum.substring(1, tempNum.length());
    				else
    					tempNum = "-" + tempString;
    				txtDisplay.setText(tempNum);
    				checkLabels();
    			}
    		}
    	}
    	
    	/*	Checks the labels in pnlCalulation to the correct number corresponding with 
    	whatever user types in.																					*/
    	public void checkLabels()	{
    		if(tempNum.equals(""))	{
    			if(lblSecondNum)	{
    				setFirstLabel();
    				lblSecond.setText("_");	}
    			else	{
    				lblFirst.setText("_");
    				lblSecond.setText("_");
    				lblResult.setText("_");
    				lblOperator.setText("?");
    			}
    		} else	{
    			if(lblSecondNum)
    				lblSecond.setText(tempNum);
    			else	{
    				lblFirst.setText(tempNum);
    				lblSecond.setText("_");
    				lblResult.setText("_");
    				lblOperator.setText("?");
    			}
    		}
    	}
    	
    /*	First Number Label, lblFirst, gets set the number1 without the .0 at the end.
    	Sets lblFirst to whatever number1 is depending on where it is needed.				*/
    	public void setFirstLabel()	{
    		Label = String.valueOf(number1);
    		if(Label.length() > 2)	{
    			if(Label.charAt(Label.length() - 1) == '0' && Label.charAt(Label.length() - 2) == '.')
    				Label = Label.substring(0, Label.length() - 2);
    		}
    		lblFirst.setText(Label);
    	}
    	public void setFirstLabel(String f)	{
    		if(f.length() > 2)	{
    			if(f.charAt(f.length() - 1) == '0' && f.charAt(f.length() - 2) == '.')
    				f = f.substring(0, f.length() - 2);
    		}
    		lblFirst.setText(f);
    	}
    	
    	public void setSecondLabel()	{
    		Label = String.valueOf(number2);
    		lblResult.setText("_");
    		if(Label.length() > 2)	{
    			if(Label.charAt(Label.length() - 1) == '0' && Label.charAt(Label.length() - 2) == '.')
    				Label = Label.substring(0, Label.length() - 2);
    		}
    		lblSecond.setText(Label);
    	}
    	public void setSecondLabel(String s)	{
    		if(s.length() > 2)	{
    			if(s.charAt(s.length() - 1) == '0' && s.charAt(s.length() - 2) == '.')
    				s = s.substring(0, s.length() - 2);
    		}
    		lblSecond.setText(s);
    	}
    	
    	//Backspace
    	public void Backspace()	{
    		if(!error)	{
    			if(txtDisplay.getText().length() < 2)	{
    				tempNum = "";
    				txtDisplay.setText("0");
    			} else	{
    				if((txtDisplay.getText().charAt(txtDisplay.getText().length() - 1) == '.' && 
    				txtDisplay.getText().charAt(txtDisplay.getText().length() - 2) == '0') ||
    				(txtDisplay.getText().length() == 2 && txtDisplay.getText().charAt(0) == '-'))	{
    					tempNum = "";
    					txtDisplay.setText("0");
    					decimalUsed = false;
    				}	else	{
    					if(txtDisplay.getText().charAt(txtDisplay.getText().length() - 1) == '.')
    					decimalUsed = false;
    					tempNum = txtDisplay.getText().substring(0, txtDisplay.getText().length() - 1);
    					txtDisplay.setText(tempNum);
    				}
    			}
    			checkLabels();
    		}
    	}
    	
    	//Clears First Number or Second Number or everything if result has been shown.
    	public void ClearExisting()	{
    		tempNum = "";
    		txtDisplay.setText("0");
    		decimalUsed = false;
    		checkLabels();
    		error = false;
    	}
    	
    	//Resets everything to startup
    	public void Clear()	{
    		tempNum = ""; sign = "0"; tempString = ""; 
    		Label = ""; R = "";
    		txtDisplay.setText("0");
    		lblFirst.setText("_");
    		lblOperator.setText("?");
    		lblSecond.setText("_");
    		lblEqual.setText("=");
    		lblResult.setText("_");
    		number1 = 0.0; number2 = 0.0; result = 0.0;
    		decimalUsed = false; secondNum = false; makeSecondTrue = false;
    		lblSecondNum = false; secondEqual = false; error = false;
    	}
    	
    	//Shows the About Calculator Dialog
    	public void showAboutDialog()	{
    /*		JDialog(Frame, Title, boolean)
    									boolean: for if you want the dialog to be a pop-up so you 
    												have to do something to make it go away or another kind of frame 
    												beside your original frame.												*/
    		JDialog dlgAbout = new JDialog(window, "About Calculator", true);
    		JTextArea txtAbout = new JTextArea(4, 4);
    		txtAbout.setLayout(new FlowLayout(FlowLayout.CENTER));
    		JPanel pnlAbout = new JPanel(new FlowLayout(FlowLayout.CENTER));
    		String about;
    		about = 	"Calculator" + "\n\n" +
    					"Version: " + VERSION + "\n" +
    					"Created: August 7, 2008" + "\n" +
    					"Author: Blmaster";
    		txtAbout.setText(about);
    		txtAbout.setEditable(false);
    		txtAbout.setBackground(new Color(90, 90, 230));
    		pnlAbout.add(txtAbout);
    		pnlAbout.setBackground(Color.blue);
    		dlgAbout.add(pnlAbout);
    		dlgAbout.setSize(180, 122);
    		dlgAbout.setLocation(window.getX() + 60, window.getY() + 50);
    		dlgAbout.setResizable(false);
    		dlgAbout.setVisible(true);
    	}
    	
    /*	Since you cant call a class (you can only call a method),
    	we have to make a instance of it. An example would be like,
    	you cant call a car so it magically appears in front of you,
    	but you can make a car. Something like that.
    	The "new" makes a new Calculator and pretty much calls
    	the code in the class contructor. 										 */
    	public static void main(String[] args)	{
    		new Calculator();
    	}
    }
    
    /*
    Version Changes:
    	0.5-	made basic layout of application.
    	1.0-	added basic (/, *, -, +) operator functions.
    	1.1-	added function: lets you keep calculating without hitting "=" button.
    	1.15-	fixed bug: wouldnt work after first time.
    	1.2-	added function: Clear button.
    	1.3-	added function: Clear Exisiting button.
    	1.4- 	reorganized code: works more efficient now.
    	1.6-	added function: change operator sign.
    	1.65- fixed bug: intefered with equal sign.
    	1.7- 	added function: MAX_INPUT for textbox
    	1.75-	fixed bug: after textbox has reached MAX_INPUT, wouldnt work.
    	1.8- 	added function: Backspace button.
    	1.85-	fixed (1.6) bug: 1.6 function wouldnt work after first use.
    	2.0- 	improved: error system, reorganized code, C, CE, Backspace Buttons.
    	2.1-	added function: menu bar. Program --> Reset, Exit
    	2.2- 	added Help --> About to menu bar.
    	2.5- 	added View --> Show Calculations to menu bar. (beta)
    	2/6- 	replaced About with a Dialog Message.
    	2.7-	fixed Show Calculations. (a lot of work)
    	2.8- 	reorganized code: show calculation function is cleaned to work more efficiently.
    	2.9- 	fixed bug: 0 button would add 0 in front of number. Ex. 032
    	2.95-	fixed (1.8) bug: Backspace wouldnt make decimal work if it erases decimal.
    	2.99-	fixed (2.5) bugs: another Show Calculation bug. wouldnt show 0.
    	3.0-	Menu Bar, Show Calculation function, removed all the ".0" at end of number. STABLE
    	3.2-	added (sqrt, %, 1/x, +/-) functions.
    	3.25-	fixed bugs: 3.2 functions intefered with labels.
    	3.4-	reorganized code: more methods for easier understanding.
    	3.5-	added Key Listener: Numper Pad in keyboard works with Calculator.
    	3.55-	fixed (3.2) bugs:	you can start over after doing functions.
    	3.59-	fixed bug: first number label always showing 0 with percent button.
    	3.6-	fixed bug: sqrt function would display error as number.
    	3.65-	fixed bug: the equal button would calculate wrongly when pressed twice in a row.
    	3.7-	added function: forces user to clear or clear exisiting or reset to get out of error.
    	3.8-	changed About dialog.
    	4.0-	FINISHED
    */
    I also attached .jar file if you just want to download and see.
    Attached Files Attached Files

  8. #7
    Coldhearth is offline Learning Programmer
    Join Date
    Oct 2008
    Posts
    88
    Rep Power
    0

    Re: Source Code: Calculator App

    I may be mistaken but this is a program that is build from only one class.
    Then this isn't realy an OO-based application isn't it? (just wondering because I want to learn the OO way)

    Nice calculator though

  9. #8
    Join Date
    May 2008
    Location
    Hell
    Posts
    3,852
    Blog Entries
    4
    Rep Power
    49

    Re: Source Code: Calculator App

    Quote Originally Posted by Coldhearth View Post
    I may be mistaken but this is a program that is build from only one class.
    Then this isn't realy an OO-based application isn't it? (just wondering because I want to learn the OO way)

    Nice calculator though
    Well to work with objects and using swing would be somewhat hard and "we could say" ""CONFUSING"". You might lose track , however! You can do it if you want, for yourself. Just grab his fine code and redo it. With one dumb object, and one with a "smart" object. The dumb object would be our main "targets" of the functions we might have, and the smart object would be the one that will calculate and answer too. The main app, would just make the simple GUI.
    Anyways GJ Blmaster !

  10. #9
    Blmaster is offline Learning Programmer
    Join Date
    Jul 2008
    Posts
    50
    Rep Power
    14

    Re: Source Code: Calculator App

    oh thanks man! the way i built this was from a step by step... like i just kept adding on functions and making them work... right now I cant even understand it that much unless i go to the beginning and work step by step! Anyways: I am working on redoing it and making it multiple classes because it is much easier to read but I will post it the code snippets subject not tutorials

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. TASM help in a calculator code
    By topman in forum Assembly
    Replies: 4
    Last Post: 06-03-2011, 01:38 PM
  2. Get pseudo code into my calculator
    By RikardE in forum C and C++
    Replies: 4
    Last Post: 12-16-2010, 03:40 PM
  3. [c++] Subnet calculator source
    By It-Cheff in forum C and C++
    Replies: 0
    Last Post: 04-14-2010, 12:54 AM
  4. Java Source Code: Calculator App
    By Blmaster in forum Classes and Code Snippets
    Replies: 10
    Last Post: 10-07-2008, 07:22 PM

Tags for this Thread

Bookmarks

Posting Permissions

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