|
|
Welcome to the Java Forums.
You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community, you will:
- have access to post topics
- communicate privately with other members (PM)
- not see advertisements between posts
- have the possibility to earn one of our surprises if you are an active member
- access many other special features that will be introduced later.
Registration is fast, simple and absolutely free so please, join our community today!
If you have any problems with the registration process or your account login, please contact us.
|
|

03-06-2008, 11:32 AM
|
|
Member
|
|
Join Date: Nov 2007
Posts: 25
|
|
|
calculator not working
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Calculator extends JFrame
{
//Create variables for Numbers being used
private double temp1=0,temp2=0, currentDisplay=0;
//
final int MAX_INPUT_LENGTH = 20;
final int INPUT_MODE = 0;
final int RESULT_MODE = 1;
final int ERROR_MODE = 2;
int displayMode;
boolean clearOnNextDigit, percent;
double lastNumber;
String lastOperator;
// create calculator buttons
private JButton jbtAdd = new JButton ("+");
private JButton jbtSubtract = new JButton ("-");
private JButton jbtDivide = new JButton ("/");
private JButton jbtMultiply = new JButton ("*");
private JButton jbtOne = new JButton ("1");
private JButton jbtTwo = new JButton ("2");
private JButton jbtThree = new JButton ("3");
private JButton jbtFour = new JButton ("4");
private JButton jbtFive = new JButton ("5");
private JButton jbtSix = new JButton ("6");
private JButton jbtSeven = new JButton ("7");
private JButton jbtEight = new JButton ("8");
private JButton jbtNine = new JButton ("9");
private JButton jbtZero = new JButton ("0");
private JButton jbtDot = new JButton (".");
private JButton jbtEquals = new JButton ("=");
// create text field for user to enter numbers in
private JTextField jtfNumber = new JTextField (15);
public Calculator ()
{
// create panel for buttons
JPanel p1 = new JPanel ();
//Set layout to gridlayout
p1.setLayout (new GridLayout (4, 4));
// add the buttons
p1.add (jbtSeven);
p1.add (jbtEight);
p1.add (jbtNine);
p1.add (jbtDivide);
p1.add (jbtFour);
p1.add (jbtFive);
p1.add (jbtSix);
p1.add (jbtMultiply);
p1.add (jbtThree);
p1.add (jbtTwo);
p1.add (jbtOne);
p1.add (jbtSubtract);
p1.add (jbtZero);
p1.add (jbtDot);
p1.add (jbtEquals);
p1.add (jbtAdd);
jtfNumber.setEditable(false);
// create panel p2 for holding text field and p1
JPanel p2 = new JPanel (new BorderLayout ());
p2.add ((jtfNumber), BorderLayout.NORTH);
p2.add (p1, BorderLayout.CENTER);
// add p2 to frame
add (p2);
// create actionlisteners
ActionListener listener1 = new OneListener ();
ActionListener listener2 = new TwoListener ();
ActionListener listener3 = new ThreeListener ();
ActionListener listener4 = new FourListener ();
ActionListener listener5 = new FiveListener ();
ActionListener listener6 = new SixListener ();
ActionListener listener7 = new SevenListener ();
ActionListener listener8 = new EightListener ();
ActionListener listener9 = new NineListener ();
ActionListener listener0 = new ZeroListener ();
ActionListener listenerA = new AddListener ();
ActionListener listenerS = new SubtractListener ();
ActionListener listenerD = new DivideListener ();
ActionListener listenerM = new MultiplyListener ();
ActionListener listenerDot = new DotListener ();
ActionListener listenerE = new EqualsListener ();
// add actionlisteners to buttons
jbtOne.addActionListener (listener1);
jbtTwo.addActionListener (listener2);
jbtThree.addActionListener (listener3);
jbtFour.addActionListener (listener4);
jbtFive.addActionListener (listener5);
jbtSix.addActionListener (listener6);
jbtSeven.addActionListener (listener7);
jbtEight.addActionListener (listener8);
jbtNine.addActionListener (listener9);
jbtZero.addActionListener (listener0);
jbtAdd.addActionListener (listenerA);
jbtSubtract.addActionListener (listenerS);
jbtDivide.addActionListener (listenerD);
jbtMultiply.addActionListener (listenerM);
jbtDot.addActionListener (listenerDot);
jbtEquals.addActionListener (listenerE);
}
/** main method */
public static void main (String [] args)
{
Calculator frame = new Calculator ();
frame.setTitle ("Calculator");
frame.setLocationRelativeTo (null); // center the frame
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setSize (200, 250);
frame.setVisible (true);
frame.setResizable(false);
}
class OneListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
addDigitToDisplay(1);
}
}
class TwoListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
addDigitToDisplay(2);
}
}
class ThreeListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
addDigitToDisplay(3);
}
}
class FourListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
addDigitToDisplay(4);
}
}
class FiveListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
addDigitToDisplay(5);
}
}
class SixListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
addDigitToDisplay(6);
}
}
class SevenListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
addDigitToDisplay(7);
}
}
class EightListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
addDigitToDisplay(8);
}
}
class NineListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
addDigitToDisplay(9);
}
}
class ZeroListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
addDigitToDisplay(0);
}
}
class DivideListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
processOperator("/");
}
}
class AddListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
processOperator("+");
}
}
class SubtractListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
processOperator("-");
}
}
class MultiplyListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
processOperator("*");
}
}
class EqualsListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
processEquals();
}
}
class DotListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
addDecimalPoint();
}
}
void setDisplayString(String s){
jtfNumber.setText(s);
}
String getDisplayString (){
return jtfNumber.getText();
}
void addDigitToDisplay(int digit){
if (clearOnNextDigit)
setDisplayString("");
String inputString = getDisplayString();
if (inputString.indexOf("0") == 0){
inputString = inputString.substring(1);
}
if ((!inputString.equals("0") || digit > 0)
&& inputString.length() < MAX_INPUT_LENGTH){
setDisplayString(inputString + digit);
}
displayMode = INPUT_MODE;
clearOnNextDigit = false;
}
void addDecimalPoint(){
displayMode = INPUT_MODE;
if (clearOnNextDigit)
setDisplayString("");
String inputString = getDisplayString();
// If the input string already contains a decimal point, don't
// do anything to it.
if (inputString.indexOf(".") < 0)
setDisplayString(new String(inputString + "."));
}
void processSignChange(){
if (displayMode == INPUT_MODE)
{
String input = getDisplayString();
if (input.length() > 0 && !input.equals("0"))
{
if (input.indexOf("-") == 0)
setDisplayString(input.substring(1));
else
setDisplayString("-" + input);
}
}
else if (displayMode == RESULT_MODE)
{
double numberInDisplay = getNumberInDisplay();
if (numberInDisplay != 0)
displayResult(-numberInDisplay);
}
}
void clearAll() {
setDisplayString("0");
lastOperator = "0";
lastNumber = 0;
displayMode = INPUT_MODE;
clearOnNextDigit = true;
}
void clearExisting(){
setDisplayString("0");
clearOnNextDigit = true;
displayMode = INPUT_MODE;
}
double getNumberInDisplay() {
String input = jtfNumber.getText();
return Double.parseDouble(input);
}
void processOperator(String op) {
if (displayMode != ERROR_MODE)
{
double numberInDisplay = getNumberInDisplay();
if (!lastOperator.equals("0"))
{
try
{
double result = processLastOperator();
displayResult(result);
lastNumber = result;
}
catch (DivideByZeroException e)
{
}
}
else
{
lastNumber = numberInDisplay;
}
clearOnNextDigit = true;
lastOperator = op;
}
}
void processEquals(){
double result = 0;
if (displayMode != ERROR_MODE){
try
{
result = processLastOperator();
displayResult(result);
}
catch (DivideByZeroException e) {
displayError("Cannot divide by zero!");
}
lastOperator = "0";
}
}
double processLastOperator() throws DivideByZeroException {
double result = 0;
double numberInDisplay = getNumberInDisplay();
if (lastOperator.equals("/"))
{
if (numberInDisplay == 0)
throw (new DivideByZeroException());
result = lastNumber / numberInDisplay;
}
if (lastOperator.equals("*"))
result = lastNumber * numberInDisplay;
if (lastOperator.equals("-"))
result = lastNumber - numberInDisplay;
if (lastOperator.equals("+"))
result = lastNumber + numberInDisplay;
return result;
}
void displayResult(double result){
setDisplayString(Double.toString(result));
lastNumber = result;
displayMode = RESULT_MODE;
clearOnNextDigit = true;
}
void displayError(String errorMessage){
setDisplayString(errorMessage);
lastNumber = 0;
displayMode = ERROR_MODE;
clearOnNextDigit = true;
}
class DivideByZeroException extends Exception{
public DivideByZeroException()
{
super();
}
public DivideByZeroException(String s)
{
super(s);
}
}
}
Anyone know why i getting an error (null pointer exception) when i push + - / * or =?
Thanks for any help
|
|

03-06-2008, 02:57 PM
|
|
Member
|
|
Join Date: Nov 2007
Posts: 25
|
|
Originally Posted by Renegade85
Anyone know why i getting an error (null pointer exception) when i push + - / * or =?
Thanks for any help
It's ok. I fixed it 
|
|

03-08-2008, 06:59 PM
|
 |
Moderator
|
|
Join Date: Dec 2007
Location: NewEngland, US
Posts: 839
|
|
Originally Posted by Renegade85
It's ok. I fixed it 
Renegade, it would be beneficial for the community if you provided how you derived your solution. Not to mention, it's said to be even beneficial for the code's owner to talk about the problem and how it was solved.
__________________
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts. to our beloved Java Forums! (closes on September 4, 2008)
Want to voice your opinion on your IDE/Editor of choice? To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts. !
Got a little Capt'n in you? (drink responsibly)
|
|

03-09-2008, 01:39 AM
|
|
Member
|
|
Join Date: Nov 2007
Posts: 25
|
|
|
The lastOperator String did not have an initial value and that was why i was getting a null pointer exception. That said, it's giving me problems again now. When you run the program, it doesn't work the way it should. It did work the first time i compiled it with an initial value for lastOperator but it's not working properly anymore.
Everytime you push an operator now, it resets the display to 0.0. I don't know why it is doing this
Last edited by Renegade85 : 03-09-2008 at 01:42 AM.
|
|

03-10-2008, 03:30 AM
|
 |
Moderator
|
|
Join Date: Dec 2007
Location: NewEngland, US
Posts: 839
|
|
Renegade, being short on time I'm afraid I can't get too deep into the logic of your code. What I've been able to see on the surface is that it works(computes) if you've already cleared the display. Have a look at sequence below.
input: 8, output: 8
input: +, output: 0.0
input: 4, output: 4
input: *, output: 4.0
input: 8, output: 8
input: =, output: 32.0
I would have a deeper look at the initial startup of the program... ie: why is it taking so long to get to the correct computations? Further note that after this simulation above, you can continue to input and get correct answers... so it seems like an error in the logic's initialization. Otherwise, the calculations work as they should.
__________________
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts. to our beloved Java Forums! (closes on September 4, 2008)
Want to voice your opinion on your IDE/Editor of choice? To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts. !
Got a little Capt'n in you? (drink responsibly)
|
|

03-10-2008, 04:27 PM
|
|
Member
|
|
Join Date: Nov 2007
Posts: 25
|
|
Originally Posted by CaptainMorgan
Renegade, being short on time I'm afraid I can't get too deep into the logic of your code. What I've been able to see on the surface is that it works(computes) if you've already cleared the display. Have a look at sequence below.
input: 8, output: 8
input: +, output: 0.0
input: 4, output: 4
input: *, output: 4.0
input: 8, output: 8
input: =, output: 32.0
I would have a deeper look at the initial startup of the program... ie: why is it taking so long to get to the correct computations? Further note that after this simulation above, you can continue to input and get correct answers... so it seems like an error in the logic's initialization. Otherwise, the calculations work as they should.
Ok, thanks. Will have a look later 
|
|
| Thread Tools |
|
|
| Display Modes |
Linear Mode
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|