我想计算字符串,如:
" -4443- + 397" //应该返回-4840
" -8844443 / -73897" //应该返回119
" 4433 * -7" //应返回-31038
" +4 * -5897" //应该返回-23588
它非常困难和棘手,我不应该如何计算字符串。 问题不是删除空白,更多的是我应该如何计算上面的字符串。 :(
public static int calc(String input) {
String noSpaces = "";
int i = 0;
while (i < input.length()) {
if (input.charAt(i) != ' ') {
noSpaces = input.charAt(i);
}
i++;
}
答案 0 :(得分:0)
这仅适用于一个数字
公共类计算器{
static int calc(String input) {
String nsp = "";
int nr1;
int nr2;
char op;
int result = 0;
for (int i = 0; input.length() > i; i++) {
if (input.charAt(i) != ' ') {
nsp = nsp + input.charAt(i);
}
}
if (nsp.charAt(0) == '+' || nsp.charAt(0) == '-') {
nr1 = Integer.parseInt(nsp.substring(0, 2));
op = nsp.charAt(2);
if (nsp.charAt(3) == '+' || nsp.charAt(3) == '-') {
nr2 = Integer.parseInt(nsp.substring(3, 5));
} else {
nr2 = Integer.parseInt(nsp.substring(3, 4));
}
} else {
nr1 = Character.getNumericValue(nsp.charAt(0));
op = nsp.charAt(1);
if (nsp.charAt(2) == '+' || nsp.charAt(2) == '-') {
nr2 = Integer.parseInt(nsp.substring(2, 4));
} else {
nr2 = Integer.parseInt(nsp.substring(2, 3));
}
}
if (op == '+') {
result = nr1 + nr2;
}
if (op == '-') {
result = nr1 - nr2;
}
if (op == '*') {
result = nr1 * nr2;
}
if (op == '/') {
result = nr1 / nr2;
}
return result;
}
}