Thread
:
My java class is killing me!!!!
View Single Post
Reply
Posted 2004-03-30, 08:28 AM in reply to
Ganga
's post starting
"no it's suppose to be first programming..."
public class Calculator implements CalculatorMVC {
private CalculatorFrame frame;
private String display; //Contents which will be display
private boolean wasLastkeyOperator=true; //show was last key a operator
private int firstOperand; //first operation
private char preOp; //Previews operator
static public void main(String[] args) {
Calculator calc = new Calculator();
CalculatorFrame frame = new CalculatorFrame("Calc");
frame.setCalculatorMVC(calc);
}
public Calculator() {
display = "0"; //int display content
preOp = '='; //int previes operator
}
public String getDisplayString() {
return display; // return content
}
public void keyClicked(char key){
if (key == 'C'){
display = "0";
firstOperand = 0;
wasLastkeyOperator = false;
}
// If it's a operator stop, else continue
//Performs the indicated mathematical operation according to whether a sequence of
if (isNumber(key)) {
if (wasLastkeyOperator){
display = ""+key;
wasLastkeyOperator = false;
}else {
display +=key;
}
}else
if (wasLastkeyOperator){
preOp = key;
}
//Calculation
else {
if (preOp=='+'){
firstOperand =firstOperand + Integer.parseInt (display);
display = Integer.toString (firstOperand);
}
if (preOp =='-') {
firstOperand =firstOperand - Integer.parseInt (display);
display = Integer.toString(firstOperand);
}
if (preOp == '*') {
firstOperand =firstOperand * Integer.parseInt (display);
display = Integer.toString(firstOperand);
}
if (preOp == '/') {
if (Integer.parseInt(display)==0){
display = "Divide by zero";
}
else{
firstOperand =firstOperand / Integer.parseInt (display);
display = Integer.toString (firstOperand);
}
}
if (preOp == '=') {
firstOperand = Integer.parseInt(display);
}
preOp =key;
wasLastkeyOperator = true;
}
}
//see if the key is a number or a operator
public boolean isNumber(char key){
if (key >= '0' && key <='9'){
return true;
}
else {
return false;
}
}
}
That's my code for the simple calculator, but my problem is everytime I click clear (C) the after calculation always wrong, it will ingnore my first number I input then it will be 0+ my second number or 0- second number or 0 * or 0 /,
like 9+9 =9, 9-9 =-9, 9*9=0, 9/9=0 where all the first number input is 0.
so I am thinking there something wrong with my codes around here:
if (key == 'C'){
display = "0";
firstOperand = 0;
wasLastkeyOperator = false;
}
edit: Nvm I just need to add a else after it. got it, thx anyway MJ.
Last edited by Ganga; 2004-03-30 at
08:50 AM
.
Profile
PM
WWW
Search
Ganga