PDA

View Full Version : need help making a java calculator



skugpezz
12-14-2009, 08:05 PM
I a stuck, how do I set the text fields to values?:shrug: My code is below.



import java.awt.*; //Contains all of the classes for creating user interfaces and for painting graphics and images
import java.applet.*;
import java.awt.event.*; //Provides interfaces and classes for dealing with different types of events fired by AWT components.

public class progcalc extends Applet implements ActionListener
{
String myBuffer;
String firstBuffer;
String secondBuffer;

String operation;

int result;
String passtoresult;

Panel row1 = new Panel();
Panel row2 = new Panel();
Panel row3 = new Panel();

Label titleLabel = new Label("Calculator", Label.CENTER);
//A Label object is a component for placing text in a container.
//A label displays a single line of read-only text.
//http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Label.html
TextField resultField = new TextField(15);
//A TextField object is a text component
//that allows for the editing of a single line of text.
//http://java.sun.com/j2se/1.4.2/docs/api/java/awt/TextField.html

Button one = new Button ("1");
Button zero = new Button ("0");
Button two = new Button ("2");
Button three = new Button ("3");
Button four = new Button ("4");
Button five = new Button ("5");
Button six = new Button ("6");
Button seven = new Button ("7");
Button eight = new Button ("8");
Button nine = new Button ("9");
Button add = new Button ("add");
Button subtract = new Button ("subtract");
Button multiply = new Button ("multiply");
Button divide = new Button ("divide");
Button equals = new Button ("equals");

public void init()
{
myBuffer="";
firstBuffer="";
secondBuffer="";

one.addActionListener(this);
// addDctionListener This class creates a labeled button.
// http://java.sun.com/j2se/1.3/docs/api/java/awt/Button.html
zero.addActionListener(this);
two.addActionListener(this);
three.addActionListener(this);
four.addActionListener(this);
five.addActionListener(this);
six.addActionListener(this);
seven.addActionListener(this);
eight.addActionListener(this);
nine.addActionListener(this);
add.addActionListener(this);
subtract.addActionListener(this);
multiply.addActionListener(this);
divide.addActionListener(this);
equals.addActionListener(this);

setBackground(Color.white);

GridLayout line1 = new GridLayout(2,1,100,10);
//The GridLayout class is a layout manager that
//lays out a container's components in a rectangular grid.

row1.setLayout(line1);
row1.add(titleLabel);row1.add(resultField);
add(row1);

GridLayout line2 = new GridLayout(3,4,2,2);
row2.setLayout(line2);
row2.add(one);row2.add(two);
row2.add(three);row2.add(four);row2.add(five);
row2.add(six);row2.add(seven);row2.add(eight);row2 .add(nine);
row2.add(zero);
add(row2);

GridLayout line3 = new GridLayout(3,2,2,2);
row3.setLayout(line3);
row3.add(add);
row3.add(subtract);
row3.add(multiply);
row3.add(divide);
row3.add(equals);
add(row3);

}


public void actionPerformed(ActionEvent event)
{

if (event.getSource ()== one)
{
resultField.setText( "1");
}
else if (event.getSource ()== two)

{
resultField.setText("2");
}
else if (event.getSource ()== three)

{
resultField.setText("3");
}
else if (event.getSource ()== four)

{
resultField.setText("4");
}
else if (event.getSource ()== five)

{
resultField.setText("5");
}
else if (event.getSource ()== six)

{
resultField.setText("6");
}
else if (event.getSource ()== seven)

{
resultField.setText("7");
}
else if (event.getSource ()== eight)

{
resultField.setText("8");
}
else if (event.getSource ()== nine)

{
resultField.setText("9");
}
else if (event.getSource ()== zero)

{
resultField.setText("0");
}
else if (event.getSource ()== add)

{
resultField.setText("+");
}
else if (event.getSource ()== divide)

{
resultField.setText("/");
}
else if (event.getSource ()== multiply)

{
resultField.setText("*");
}
else if (event.getSource ()== equals)

{
resultField.setText("=");
}
if (event.getSource ()== equals);
{

}
}

}

eshbach
12-14-2009, 08:43 PM
You don't want the giant column of if/else if in the actionPerformed method. Instead, set the actionCommand of the buttons to something useful like "1", "2"... and then do something like resultField.setText(resultField.getText() + event.getActionCommand());

EDIT: Since you seem a little confused, here's something to work with. THIS IS NOT A PERFECT EXAMPLE. For one, it does not implement correct Order of Operations, and it has several other bugs (some are carried over from your code and some are new). It does, however, work reasonably well as a demonstration of how to do this sort of thing. So, with this, you should be able to get the calculator working the way you want.



import java.awt.*; //Contains all of the classes for creating user interfaces and for painting graphics and images
import java.applet.*;
import java.awt.event.*; //Provides interfaces and classes for dealing with different types of events fired by AWT components.

public class Calculator extends Applet implements ActionListener
{
private TextField resultField;
private boolean doReset;

public void init()
{
Panel row1 = new Panel();
Panel row2 = new Panel();
Panel row3 = new Panel();

Button one = new Button("1");
Button zero = new Button("0");
Button two = new Button("2");
Button three = new Button("3");
Button four = new Button("4");
Button five = new Button("5");
Button six = new Button("6");
Button seven = new Button("7");
Button eight = new Button("8");
Button nine = new Button("9");
Button add = new Button("add");
Button subtract = new Button("subtract");
Button multiply = new Button("multiply");
Button divide = new Button("divide");
Button equals = new Button("equals");

Label titleLabel = new Label("Calculator", Label.CENTER);
resultField = new TextField(15);


one.addActionListener(this);
one.setActionCommand("1");
zero.addActionListener(this);
zero.setActionCommand("0");
two.addActionListener(this);
two.setActionCommand("2");
three.addActionListener(this);
three.setActionCommand("3");
four.addActionListener(this);
four.setActionCommand("4");
five.addActionListener(this);
five.setActionCommand("5");
six.addActionListener(this);
six.setActionCommand("6");
seven.addActionListener(this);
seven.setActionCommand("7");
eight.addActionListener(this);
eight.setActionCommand("8");
nine.addActionListener(this);
nine.setActionCommand("9");
add.addActionListener(this);
add.setActionCommand(" + ");
subtract.addActionListener(this);
subtract.setActionCommand(" - ");
multiply.addActionListener(this);
multiply.setActionCommand(" * ");
divide.addActionListener(this);
divide.setActionCommand(" / ");
equals.addActionListener(this);
equals.setActionCommand(" = ");

setBackground(Color.white);

GridLayout line1 = new GridLayout(2, 1, 100, 10);
// The GridLayout class is a layout manager that
// lays out a container's components in a rectangular grid.

row1.setLayout(line1);
row1.add(titleLabel);
row1.add(resultField);
add(row1);

GridLayout line2 = new GridLayout(3, 4, 2, 2);
row2.setLayout(line2);
row2.add(one);
row2.add(two);
row2.add(three);
row2.add(four);
row2.add(five);
row2.add(six);
row2.add(seven);
row2.add(eight);
row2.add(nine);
row2.add(zero);
add(row2);

GridLayout line3 = new GridLayout(3, 2, 2, 2);
row3.setLayout(line3);
row3.add(add);
row3.add(subtract);
row3.add(multiply);
row3.add(divide);
row3.add(equals);
add(row3);

}

public void actionPerformed(ActionEvent event)
{
String currentResult = doReset ? "" : this.resultField.getText();
this.resultField.setText(currentResult + event.getActionCommand());

if (event.getActionCommand().trim().equalsIgnoreCase("="))
{
String[] terms = currentResult.split(" ");
int result = 0;

for(int i = 0; i < terms.length - 1; i += 1)
{
String term = terms[i].trim();
String nextTerm = terms[i+1].trim();

if (term.equalsIgnoreCase("+"))
{
result += Integer.parseInt(nextTerm);
}
else if (term.equalsIgnoreCase("-"))
{
result -= Integer.parseInt(nextTerm);
}
else if (term.equalsIgnoreCase("*"))
{
result *= Integer.parseInt(nextTerm);
}
else if (term.equalsIgnoreCase("/"))
{
result /= Integer.parseInt(nextTerm);
}
else if (i == 0)
{
result = Integer.parseInt(term);
}
}

this.resultField.setText((this.resultField.getText () + Integer.toString(result)));
this.doReset = true;
}
else
{
this.doReset = false;
}
}

}

skugpezz
12-15-2009, 02:59 PM
thanks alot man I will test it out and let you how it goes when i get home form school :D

skugpezz
12-15-2009, 09:49 PM
the code work, but I understand none of it:confused::shrug:

could you add some comments , I am really new to this

eshbach
12-15-2009, 11:51 PM
the code work, but I understand none of it:confused::shrug:

could you add some comments , I am really new to this

Sure, I'll give you a basic explanation and then post the commented code for you.

Basic Explanation:
The init() method of the Applet creates all of the buttons for the calculator. Each button is assigned a unique "Action Command" which is carried along in the ActionEvent object that is generated when a user clicks a button and passed into the actionPerformed() method of your ActionListener.

The actionPerformed() method looks at the actionCommand property of the ActionEvent object it takes as a parameter. The actionCommand is then appended to the end of the text in the resultField TextField object, similar to how a calculator may show the current 'line of input' as the user presses the buttons. The user presses '2', the calculator displays '2'; the user presses '+', the calculator displays '2 + '; the user presses '3', the calculator displays '2 + 3'.

When the user presses the "equals" button, then actionPerformed() method parses the string being displayed ('2 + 3') by splitting the display string on the 'space' character and analyzing each term (see code). When the result is computed, the calculator appends that to the display and so the user sees '2 + 3 = 5'. At this time the method sets the instance variable "doReset" to true, and the next time a button is clicked, the display field is first erased so that the user starts over with a blank line to solve a new problem.



Commented Code:


import java.awt.*; //Contains all of the classes for creating user interfaces and for painting graphics and images
import java.applet.*;
import java.awt.event.*; //Provides interfaces and classes for dealing with different types of events fired by AWT components.

/**
* The Calculator class is a graphical applet which implements the
* functionality of a simple 5-function integer calculator.
* @author Skugpezz, Eshbach
* @version 12.16.09
*/
public class Calculator extends Applet implements ActionListener
{
// These fields are used from multiple methods within the class,
// as such they are declared as instance variables, at the top level.
// These fields are private because they are not used from any other
// classes and represent the state of this class, which should not be
// modified from the outside.
private TextField resultField;
private boolean doReset;

/**
* The init method of this applet sets up the GUI and initializes the
* instance variables to their default state, making the calculator
* ready to use.
*/
public void init()
{
// These panels will be used as containers for the various
// GUI controls on the calculator such as buttons and text boxes.
Panel row1 = new Panel();
Panel row2 = new Panel();
Panel row3 = new Panel();

// The GridLayout class is a layout manager that
// organizes a container's components into a rectangular grid of
// equally sized and spaced cells. Each row Panel will have its
// own GridLayout manager defining a different size for its grid.
// The parameters for the constructor are rows, columns,
// horizontal gap, and vertical gap.
GridLayout line1 = new GridLayout(2, 1, 100, 10);
GridLayout line2 = new GridLayout(3, 4, 2, 2);
GridLayout line3 = new GridLayout(3, 2, 2, 2);

// These Button objects represent the buttons one finds on a normal
// calculator. The String parameter passed to their constructor
// defines the text which will be displayed on the face of the button.
Button one = new Button("1");
Button zero = new Button("0");
Button two = new Button("2");
Button three = new Button("3");
Button four = new Button("4");
Button five = new Button("5");
Button six = new Button("6");
Button seven = new Button("7");
Button eight = new Button("8");
Button nine = new Button("9");
Button add = new Button("add");
Button subtract = new Button("subtract");
Button multiply = new Button("multiply");
Button divide = new Button("divide");
Button equals = new Button("equals");

// A label is a static text element. The title label defined here
// will be used to set the text shown in the title bar of the applet.
Label titleLabel = new Label("Calculator", Label.CENTER);


/*
* Now we're done defining the elements of the GUI, we can start putting
* them together to create the look and functionality of a calculator.
*/

// This line initializes resultField instance variable of this class
// to a new (empty) TextField with room to display 15 characters.
this.resultField = new TextField(15);

// For each button, we add an action listener which is this class.
// The action listener defines a method called 'actionPerformend'
// which is called whenever a button subscribed to the listener
// is clicked by the user. The 'acitonPerformed' method takes a
// single parameter called the ActionEvent. This even contains
// information about what the user did so that appropriate action
// can be taken. In this case, we are setting the 'actionCommand'
// property of the ActionEvent to the arithmetic value of the button.
one.addActionListener(this);
one.setActionCommand("1");
zero.addActionListener(this);
zero.setActionCommand("0");
two.addActionListener(this);
two.setActionCommand("2");
three.addActionListener(this);
three.setActionCommand("3");
four.addActionListener(this);
four.setActionCommand("4");
five.addActionListener(this);
five.setActionCommand("5");
six.addActionListener(this);
six.setActionCommand("6");
seven.addActionListener(this);
seven.setActionCommand("7");
eight.addActionListener(this);
eight.setActionCommand("8");
nine.addActionListener(this);
nine.setActionCommand("9");
add.addActionListener(this);
add.setActionCommand(" + ");
subtract.addActionListener(this);
subtract.setActionCommand(" - ");
multiply.addActionListener(this);
multiply.setActionCommand(" * ");
divide.addActionListener(this);
divide.setActionCommand(" / ");
equals.addActionListener(this);
equals.setActionCommand(" = ");

// Sets the background color of the applet to White (0xFFFFFF).
this.setBackground(Color.white);

// Set the layout of row1 to the Grid layout defined by line1.
row1.setLayout(line1);

// Add the title Label control to the row1 Panel.
row1.add(titleLabel);

// Add the result TextField control to the row1 Panel.
row1.add(resultField);

// Add the row1 Panel to the applet.
this.add(row1);

// Set the layout of row2 to the Grid layout defined by line2.
row2.setLayout(line2);

// Add each of the numeric buttons to row2.
row2.add(one);
row2.add(two);
row2.add(three);
row2.add(four);
row2.add(five);
row2.add(six);
row2.add(seven);
row2.add(eight);
row2.add(nine);
row2.add(zero);

// Add the row2 Panel to the applet.
this.add(row2);

// Set the layout of row3 to the Grid layout defined by line3.
row3.setLayout(line3);

// Add each of the operator buttons to row3.
row3.add(add);
row3.add(subtract);
row3.add(multiply);
row3.add(divide);
row3.add(equals);

// Add the row3 Panel to the applet.
this.add(row3);

/*
* The applet has now been initialized. It is ready to use and awaits
* input from the user before any more code is executed.
*/
}

/**
* The actionPerformed method of this ActionListener handles the button-
* clicks of the calculator's controls. When a user clicks a numeric
* button, the number is simply concatenated to the display. When a user
* clicks an operator button other than equals, the operator is inserted
* after a space in the display, and serves as a division between numbers.
* When the equals button is clicked, the method parses the String that now
* exists in the resultField and performs the operations being displayed
* in the order in which they appear.
*
* @param event The ActionEvent containing information about what button
* was clicked by the user.
*/
public void actionPerformed(ActionEvent event)
{
// The first lines here determine whether to reset the resultField
// display or to simply concatenate the event's actionCommand value
// to the end of the currently display string.

// If doReset is true, set the currentResult to the empty String;
// otherwise, set it to the text contained in resultField.
String currentResult = doReset ? "" : this.resultField.getText();

// Set the String displayed in resultField to the concatenation of
// the currentResult String and the actionCommand of the event,
// which was set in the init() method.
this.resultField.setText(currentResult + event.getActionCommand());

// Check to see if the user clicked the equals button. We trim the
// actionCommand String so that any whitespace is ignored. We also
// disregard the case, although it should not matter for '='.
if (event.getActionCommand().trim().equalsIgnoreCase("="))
{
// Make a String[] of the terms in the currentResult by splitting
// on the space character. For instance, if currentResult is the
// value "2 + 5 * 3", then we make terms a String array with the
// values {2,+,5,*,3};
String[] terms = currentResult.split(" ");

// Make an integer to be used to hold the running total as we parse
// and evaluate each term in the array created above.
int result = 0;

// We now loop through the String array created above and evaluate
// each term as we come to it.
for(int i = 0; i < terms.length - 1; i += 1)
{
// Get the current term and the next term from the array,
// and remove any whitespace around the characters so that
// we can easily check the String objects for equality.
String term = terms[i].trim();
String nextTerm = terms[i+1].trim();

// First we check to see if the current term is an operator.
if (term.equalsIgnoreCase("+"))
{
// If the current term is '+', then we add the next term
// to our running total.
result += Integer.parseInt(nextTerm);
}
else if (term.equalsIgnoreCase("-"))
{
// If the current term is '-', then we subtract the next
// term from our running total.
result -= Integer.parseInt(nextTerm);
}
else if (term.equalsIgnoreCase("*"))
{
// If the current term is '*', then we multiply the running
// total by the next term.
result *= Integer.parseInt(nextTerm);
}
else if (term.equalsIgnoreCase("/"))
{
// If the current term is '/', then we divide the running
// total by the next term.
result /= Integer.parseInt(nextTerm);
}
else if (i == 0)
{
// If the current term is not one of the operators and this
// is the first term in the array, set the running total
// to the current term.
result = Integer.parseInt(term);
}
}

// Append the calculated result to the text displayed
// in resultField.
this.resultField.setText((this.resultField.getText () + Integer.toString(result)));

// Set the doReset instance variable to true so that the next time
// the user clicks a button, the display will be blanked.
this.doReset = true;
}
else
{
// If we did not compute a result (the button clicked was not '='),
// then make sure we don't reset the display next time.
this.doReset = false;
}
}

}

skugpezz
12-17-2009, 12:00 AM
Thank again, I will study these codes some more.

cdolphin
12-24-2009, 10:00 AM
Skung, you are using code generated by a gui creator of some sort... If you are unable to understand the basic syntax of that program, you should start with some more generalized java work. Nonethelss, in answer to your question, the setText(String s ) of the JTextField class will set the display text of said object...
Check the API at java.com if you ever need to know the name of a method, rather than how to do something :P.
Send me a PM if you need more help.


I just worked through the code a bit more....
And to whoever posted, teranary operators are unneeded at a low level like this, we are going for readibility not bare-bones efficiency....
Instead of introducing all of those string manipulations, use the Event.getSource method.





import java.awt.*; //Contains all of the classes for creating user interfaces and for painting graphics and images
import java.applet.*;
import java.awt.event.*; //Provides interfaces and classes for dealing with different types of events fired by AWT components.

public class Calculator extends Applet implements ActionListener
{
private TextField resultField;
private boolean doReset;

public void init()
{
Panel row1 = new Panel();
Panel row2 = new Panel();
Panel row3 = new Panel();

Button[] numButtons = new Button[10];
for(int i =0; i <10; i ++)
{
numButtons[i] = new Button(i + "");
numButtons[i].addActionListener(this);
numButtons[i].setActionCommand(i + "");
}
Button add = new Button("add");
Button subtract = new Button("subtract");
Button multiply = new Button("multiply");
Button divide = new Button("divide");
Button equals = new Button("equals");

Label titleLabel = new Label("Calculator", Label.CENTER);
resultField = new TextField(15);


add.addActionListener(this);
add.setActionCommand(" + ");
subtract.addActionListener(this);
subtract.setActionCommand(" - ");
multiply.addActionListener(this);
multiply.setActionCommand(" * ");
divide.addActionListener(this);
divide.setActionCommand(" / ");
equals.addActionListener(this);
equals.setActionCommand(" = ");

setBackground(Color.white);

GridLayout line1 = new GridLayout(2, 1, 100, 10);
// The GridLayout class is a layout manager that
// lays out a container's components in a rectangular grid.

row1.setLayout(line1);
row1.add(titleLabel);
row1.add(resultField);
add(row1);

GridLayout line2 = new GridLayout(3, 4, 2, 2);
row2.setLayout(line2);
for(Button b : numButtons)
row2.add(b);
add(row2);

GridLayout line3 = new GridLayout(3, 2, 2, 2);
row3.setLayout(line3);
row3.add(add);
row3.add(subtract);
row3.add(multiply);
row3.add(divide);
row3.add(equals);
add(row3);

}

public void actionPerformed(ActionEvent event)
{
//no need to use a teranary operator for a beginner...
String currentResult = "";
if( !doReset)
currentResult = this.resultField.getText();
this.resultField.setText(currentResult + event.getActionCommand());
//use event.getSource() much easier and more effective
if (event.getActionCommand().trim().equalsIgnoreCase("="))
{
String[] terms = currentResult.split(" ");
int result = 0;

for(int i = 0; i < terms.length - 1; i += 1)
{
String term = terms[i].trim();
String nextTerm = terms[i+1].trim();

if (term.equalsIgnoreCase("+"))
{
result += Integer.parseInt(nextTerm);
}
else if (term.equalsIgnoreCase("-"))
{
result -= Integer.parseInt(nextTerm);
}
else if (term.equalsIgnoreCase("*"))
{
result *= Integer.parseInt(nextTerm);
}
else if (term.equalsIgnoreCase("/"))
{
result /= Integer.parseInt(nextTerm);
}
else if (i == 0)
{
result = Integer.parseInt(term);
}
}

this.resultField.setText((this.resultField.getText () + Integer.toString(result)));
this.doReset = true;
}
else
{
this.doReset = false;
}
}

}

eshbach
02-12-2010, 10:03 PM
I just worked through the code a bit more....
And to whoever posted, teranary operators are unneeded at a low level like this, we are going for readibility not bare-bones efficiency....
Instead of introducing all of those string manipulations, use the Event.getSource method.




I'm sure there's nothing more efficient about using a ternary operator instead of an if-else block. You're still looking at a compare-jump-assign instruction sequence. I just personally thing ternary operators are more readable for making conditional assignments, but you're right, it didn't even cross my mind that an introductory Java class might skip over the ternary operator for a while.

I'm not sure what you mean by using event.getSource to eliminate some string manipulation. I would certainly agree that avoiding unneccessary string operations would be preferrable, but I don't see how you would do that in this case. The only thing I see that you might be talking about is the line
if (event.getActionCommand().trim().equalsIgnoreCase("=")), but I'm not sure what alternative you're proposing.

I'll freely admit, however, that I'm no expert on Java GUI coding. The last time I wrote a non-trivial Java GUI app was my Sophomore year of college, almost 5 years ago now. Most GUIs I've had to write since I got a real programming job are Win32, and I often forget about some of the convenient things you can do with an OO event-driven framework that don't really translate to C and message pumping.