【发布时间】:2011-10-31 16:02:34
【问题描述】:
我刚刚学习了 java,并问了一个关于我的单行计算器的问题,它不再给出错误但它计算错误。 这是代码
import java.util.Scanner;
public class omg {
public static void main(String args[]) {
int fnum,snum,anum = 0;
String strtype;
char[] testchar;
char currentchar;
int machinecode = 0;
String tempnumstr;
int operatorloc = 0;
char[] tempnum = new char[256];
Scanner scan = new Scanner(System.in);
System.out.println("Enter The Calculation: ");
strtype = scan.nextLine();
testchar = strtype.toCharArray();
for(int b = 0; b < testchar.length; b++)
{
currentchar = testchar[b];
if(currentchar == '+') {
machinecode = 1;
operatorloc = b;
}
else if(currentchar == '-') {
machinecode = 2;
operatorloc = b;
}
else if(currentchar == '*') {
machinecode = 3;
operatorloc = b;
}
else if(currentchar == '/') {
machinecode = 4;
operatorloc = b;
}
}
for(int t = 0;t < operatorloc;t++) {
tempnum[t] = testchar[t];
}
tempnumstr = new String(tempnum).trim();
fnum = Integer.parseInt(tempnumstr);
for(int temp = operatorloc;temp < testchar.length;temp++) {
for(int t = 0;t<(testchar.length-operatorloc);t++) {
tempnum[t] = testchar[temp];
}
}
tempnumstr = new String(tempnum).trim();
snum = Integer.parseInt(tempnumstr);
switch(machinecode) {
case 1:
anum = fnum + snum;
break;
case 2:
anum = fnum - snum;
break;
case 3:
anum = fnum * snum;
break;
case 4:
anum = fnum / snum;
}
System.out.println(anum);
}
}
这段代码会给我 8+8 = 96, 而这显然是不正确的。
【问题讨论】:
-
恭喜你刚刚学会了java
-
看看
substring方法:download.oracle.com/javase/6/docs/api/java/lang/…
标签: java calculator