Java Calculator - input decimal point

Java Calculator - inputting decimal point

Page 1 of 1

1 Replies - 19806 Views - Last Post: 24 September 2007 - 09:31 PM Rate Topic: -----

#1 marckiestar   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 21
  • Joined: 21-August 07

Java Calculator - input decimal point

Post icon  Posted 24 September 2007 - 09:03 PM

Hi! My calculator is working only for whole numbers. It could display answers with decimal points, but this could not accept input of a decimal point. I've been working for this for more than a week now. And I have only one thing to do, then its done. I've made a KeyListener but it doesnt work, can you please modify this. It has an error " cannot be overriden. " This is due tomorrow, I need this.

The error is on the part that i made comment, the key Listener. The problem is that I could not input decimal point. Please see the code below.

// Filename : Calc.Java ---------------------run the program here

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class Calc {

	public static void main(String[] args) {
		JFrame window = new JFrame("Kilat KalCuLator");
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.setContentPane(new CalcGUI());
		window.pack();
		window.show();
	}//end main
}//endclass Calc



//Filename: CalcGUI
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.KeyListener;


class CalcGUI extends JPanel {


	//=============================================== instance variables
	//--- variable for GUI elements
	private JTextField _displayField;		// display result / input.
	//--- variables representing state of the calculator
	private boolean	_startNumber = true;  // true: num key next
	private double		_resultValue = 0.0;	 // result so far
	private String	 _previousOp  = "=";   // previous operation
	//end instance variables

	//-------------------------------------------- static (class) variables
	private static final Font BIGGER_FONT = new Font("monspaced", Font.PLAIN, 24);


	//====================================================== constructor
	public CalcGUI() {
		//--- Display field
		_displayField = new JTextField("0", 12);
		_displayField.setHorizontalAlignment(JTextField.RIGHT);
		_displayField.setFont(BIGGER_FONT);

		//--- Clear button
		JButton clearButton = new JButton("CLEAR");
		clearButton.setFont(BIGGER_FONT);
		clearButton.addActionListener(
			new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					action_clear();
				}
			}
		);

		//--- Use one listener for all numeric keys.
		ActionListener numListener =
			new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					action_num(e);  // process it below
				}
			};

		//--- Layout numeric keys in a grid.
		//--- Use the characters in a string as a guide
		//--- for producing the numeric keys.
		String buttonOrder = "789456123 0 ";
		JPanel buttonPanel = new JPanel(new GridLayout(5, 3));
		for (int i = 0; i < buttonOrder.length(); i++) {
			String keyTop = buttonOrder.substring(i, i+1);
			if (keyTop.equals(" ")) {
				buttonPanel.add(new JLabel(""));
			} else {
				JButton b = new JButton(keyTop);
				b.addActionListener(numListener);
				b.setFont(BIGGER_FONT);
				buttonPanel.add(b);
			}
		}

		//--- Create an ActionListener that will be used for
		//--- all of the operator buttons.
		ActionListener opListener =
			new ActionListener() {
				public void actionPerformed(ActionEvent e) {
				   action_op(e);
				}//endmethod actionPerformed
		   };


		//--- Create panel with gridlayout to hold operator buttons.
		//--- Use array of button names to create buttons in a loop.
		JPanel opPanel = new JPanel(new GridLayout(5, 1));
		String[] opOrder = {"+", "-", "*", "/", "=","%"};
		for (int i = 0; i < opOrder.length; i++) {
			JButton b = new JButton(opOrder[i]);
			b.addActionListener(opListener);
			b.setFont(BIGGER_FONT);
			opPanel.add(b);
			}
			JButton c= new JButton(".");
			c.setFont(BIGGER_FONT);
			opPanel.add(c);
							 // This may be the error but I dont know where to put this, please modify
 //because its not working, I dont really know how to use the KeyListener, I tried to write this code 
// also below but it does not  work, please look at the code i made from here onwards

		/**c.addKeyListener( new KeyListener (){
				public void keyPressed( KeyEvent e){
					_displayField.setText(".");
				}
				});*/




		//--- Layout this, the top level, panel.
		this.setLayout(new BorderLayout());
		this.add(_displayField, BorderLayout.NORTH );
		this.add(buttonPanel  , BorderLayout.CENTER);
		this.add(opPanel	  , BorderLayout.EAST  );
		this.add(clearButton  , BorderLayout.SOUTH );
	}//end constructor


	//============================================================ action_op
	// Called by the action listener for all op buttons.
	private void action_op(ActionEvent e) {
		// The calculator is always in one of two states.
		// 1. A number must be entered next (so this operator is wrong).
		// 2. An operator must be entered next (so we're ok).
		if (_startNumber) { // Error: needed number, not operator
			action_clear();
			_displayField.setText("ERROR");
		} else {
			_startNumber = true;  // Next thing must be a number
			try {
				// Get the value from display field, convert it, do prev op
				// If this is the first op, _previousOp will be =.
				int currentValue = Integer.parseInt(_displayField.getText());
				double currentValuez = Double.parseDouble(_displayField.getText());
				//int d=Integer.parseInt(c);

				if (_previousOp.equals("=")) {
					_resultValue = currentValue;
				} else if (_previousOp.equals("+")) {
					_resultValue += currentValuez;
				} else if (_previousOp.equals("-")) {
					_resultValue -= currentValuez;
				} else if (_previousOp.equals("*")) {
					_resultValue *= currentValuez;
				} else if (_previousOp.equals("/")) {
					_resultValue /= currentValue;
				} else if (_previousOp.equals("%")) {
					_resultValue %= currentValue;
				}
				/**else if(_previousOp.equals("."))
				{
					c.addKeyListener( new KeyListener(){
						public void action(KeyEvent l){
							_displayField.setText(".");
					}
				});*/

				/**c.addKeyListener( new KeyListener (){
				public void keyTyped( KeyEvent e){
					_displayField.setText(".");
				}
				});*/


				/**} else if (_previousOp.equals(".")) {
					_displayField.setText(currentValue+"."+currentValue);
				}*/
				_displayField.setText(""+_resultValue);

			} catch (NumberFormatException ex) {
				action_clear();
				_displayField.setText("Error");
			}

			//--- set _previousOp for the next operator.
			_previousOp = e.getActionCommand();
		}//endif _startNumber
	}//endmethod action_op


	//======================================================== action_num
	// Called by the action listener for numeric keys
	private void action_num(ActionEvent e) {
		String digit = e.getActionCommand(); // gets text from digit key
		if (_startNumber) {
			// This is the first digit, clear field and set
			_displayField.setText(digit);
			_startNumber = false;
		} else {
			// Add this digit to the end of the display field
			_displayField.setText(_displayField.getText() + digit);
		}
	}//endmethod action_num


	//=============================================== logic action_clear
	// Called by the action listener for the Clear button
	public void action_clear() {
		_startNumber = true;
		_displayField.setText("0");
		_resultValue = 0.0;
		_previousOp  = "=";




	}//endmethod action_clear


	/**c.addActionListener( new ActionListener (){
		public void actionPerformed( ActionEvent e){
			_displayField.setText(".");
		}
		});*/

}//endclass CalcGUI



This post has been edited by marckiestar: 24 September 2007 - 09:37 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Java Calculator - input decimal point

#2 1lacca   User is offline

  • code.rascal
  • member icon

Reputation: 44
  • View blog
  • Posts: 3,822
  • Joined: 11-August 05

Re: Java Calculator - input decimal point

Posted 24 September 2007 - 09:31 PM

If you post the entire error message, then we could look right at the row that contains the error. If you don't, we must either look at the whole code line by line, or create a project and enter your code to see what error message is reported by the compiler. Question: do you think, you'll get an answer sooner if you post the error message, or if you don't? (hint: we are people as well, we work, study and have to party and also sleep as well, and we do it jsut for fun, we don't get paid for answering)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1