I'm beginner in Java Android developing. I'm using Eclipse SDK 3.6.1 version. I'm trying to do a simple calculator. I have one problem how to input a fractional number? There is my code:
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnNum0Id:
case R.id.btnNum1Id:
case R.id.btnNum2Id:
case R.id.btnNum3Id:
case R.id.btnNum4Id:
case R.id.btnNum5Id:
case R.id.btnNum6Id:
case R.id.btnNum7Id:
case R.id.btnNum8Id:
case R.id.btnNum9Id:
String inDigit = ((Button)view).getText().toString();
if (inStr.equals("0")) {
inStr = inDigit;
} else {
inStr += inDigit;
}
t开发者_如何学JAVAekstas.setText(inStr);
if (Operator == '=') {
rezult = 0;
Operator = ' ';
}
break;
case R.id.btnAddId:
aritmetika();
Operator = '+';
break;
case R.id.btnSubId:
aritmetika();
Operator = '-';
break;
case R.id.btnMulId:
aritmetika();
Operator = '*';
break;
case R.id.btnDivId:
aritmetika();
Operator = '/';
break;
case R.id.btnSqrtId:
aritmetika();
Operator = 'a';
break;
case R.id.btnEqualId:
aritmetika();
Operator = '=';
break;
case R.id.dot:
aritmetika();
Operator = '.';
break;
case R.id.btnClearId:
rezult = 0;
inStr = "0";
Operator = ' ';
tekstas.setText("0");
break;
}
}
private void aritmetika() {
int inNum = Integer.parseInt(inStr);
if (Operator == ' ') {
rezult = inNum;
} else if (Operator == '+') {
rezult += inNum;
} else if (Operator == '-') {
rezult -= inNum;
} else if (Operator == '*') {
rezult *= inNum;
} else if (Operator == '/') {
rezult /= inNum;
} else if (Operator == 'a') {
rezult = (float)Math.sqrt(rezult);
} else if (Operator == '.') {
String rezult2 = inStr+'.';
//need fractional number
} else if (Operator == '=') {
// tolesnis veiksmas
}
tekstas.setText(String.valueOf(rezult));
}
}
I'm thinking how to make a fractional number.
For Fractional Number, you can use /
like 3/4
or a decimal notation like 1.23
is very much there. Are you facing any specific issues!?
UPDATE AFTER NEGATIVE VOTE, AND MORE DESCRIPTION IN QUESTION :-P
You can have a dot(.) button as you would have any other button. put a .
as its text.
Append all the things in the edit text, and on the click of your =
button, take everything out from the edit text as string, first treat the mathematical signs as +,-,x,/
as delimiters, and convert your values to post-fix notation, store them in an array and then calculate.
You can put the dot handling together with number handling, not as a separate operator (treat the dot as a part of a number). If you use double as the type of rezult, you can do parseDouble instead of parseInt on the whole string with numbers and dots.
This design is very limiting. You should try to make a simple tokenizer and parser that creates a parse tree of operations. This would be a much more rewarding experience.
精彩评论