Saturday, December 27, 2008

Making a Simple Calculator

I want to make a Calculator !


...
....
public class MyCalculator extends MIDlet implements CommandListener
{
...
....

After that, I preparing for the Item that i want to display in the screen
The item is :
3 TextField for inputing first value, second value, and the result.
1 ChoiceGroup for selecting the operator.
2 Command, one for exit, one for Calc(ulating) :D.
So..

..
...
private TextField fv = new TextField("First Value", "", 10, TextField.NUMERIC);
private TextField sv = new TextField("Second Value", "", 10, TextField.NUMERIC);
private TextField r = new TextField("Result", "", 50, TextField.ANY);
String cgOperator[] = {"Divide","Times","Add","Subtract"};
private ChoiceGroup operator = new ChoiceGroup("Operator",ChoiceGroup.EXCLUSIVE, cgOperator, null);
.....
.....

And of course, the commandAction() method..

...
..
public void commandAction(Command c, Displayable d) {
// If it's our exitCommand, destroy ourselves
if(c.getLabel().equals("Exit")) {
notifyDestroyed();
}else if(c.getLabel().equals("Calc")) {
int first_value = Integer.parseInt(fv.getString());
int second_value = Integer.parseInt(sv.getString());
double result = 0;
if(operator.isSelected(0))
{
result = first_value / second_value;
}else if(operator.isSelected(1))
{
result = first_value * second_value;
}else if(operator.isSelected(2))
{
result = first_value + second_value;
}else if(operator.isSelected(3))
{
result = first_value - second_value;

}
r.setString(""+result+""); // <<< (i can't parseDouble() it.. :D)
}
}
...
..

Compile it, Deploy it, and I get my MIDlet Calculator !!! yeah

No comments:

Post a Comment