我对标题所暗示的事情有疑问。我需要对字符串进行标记,确定操作以解决它,将数字转换为int
类型并返回表达式。
就解析和标记化而言,我到底做错了什么?在我尝试使用stringSplit之前,一切似乎都没问题。唯一允许的库函数是Integer.parseInt()
和split()
。 StackOverflow上有很多东西需要帮助,但没有一个不使用这两个库函数。这是我到目前为止的代码:
public static void main(String[] args)
{
String a[] = {"12 + 34", "56 - 78", "99 * 99", "10 / 3"};
stringSplit(a, ',');
}
public static int parseInt(String a)
{
int i;
int sum = 0;
double x = Integer.parseInt(a);
for(i = 0; i < a.length(); i++)
sum = sum + x;
System.out.printf("%s = %d\n", sum);
}
最终结果应该类似于:
12 + 34 = 46.00
56 - 78 = -22.00
之类的。我不是真的在寻找答案。更多的是导致我的回答。提前感谢您的任何帮助!
答案 0 :(得分:2)
这是您似乎尝试做的工作版本。我在空间(" "
)上拆分输入数组的每个元素,然后提取出两个操作数和一个运算符。我还把支票除以零。
public static void main(String[] args) throws Exception {
String a[] = {"12 + 34", "56 - 78", "99 * 99", "10 / 3"};
stringProcess(a);
}
public static void stringProcess(String[] a) {
for (int i=0; i < a.length; ++i) {
String[] parts = a[i].split(" ");
double operand1 = Double.parseDouble(parts[0]);
String operator = parts[1];
double operand2 = Double.parseDouble(parts[2]);
double result = 0.0;
switch (operator) {
case "+":
result = operand1 + operand2;
break;
case "-":
result = operand1 - operand2;
break;
case "*":
result = operand1 * operand2;
break;
case "/":
if (operand2 == 0) {
throw new IllegalArgumentException("Divide by zero!");
}
result = operand1 / operand2;
break;
}
System.out.println(operand1 + " " + operator + " " + operand2 +
" = " + String.format( "%.2f", result));
}
}
<强>输出:强>
12.0 + 34.0 = 46.00
56.0 - 78.0 = -22.00
99.0 * 99.0 = 9801.00
10.0 / 3.0 = 3.33
答案 1 :(得分:1)
public class Test{
public static void main(String[] args) {
String a[] = { "12 + 34", "56 - 78", "99 * 99", "10 / 3" };
parseInt(a);
}
public static void parseInt(String[] a) {
int sum = 0;
for (int i = 0; i < a.length; i++) {
String[] pieces = a[i].split(" ");
if("+".equals(pieces[1])){
sum = Integer.valueOf(pieces[0]) + Integer.valueOf(pieces[2]);
}else if("-".equals(pieces[1])){
sum = Integer.valueOf(pieces[0]) - Integer.valueOf(pieces[2]);
}else if("*".equals(pieces[1])){
sum = Integer.valueOf(pieces[0]) * Integer.valueOf(pieces[2]);
}else {
sum = Integer.valueOf(pieces[0]) / Integer.valueOf(pieces[2]);
}
System.out.println("sum" + sum);
}
}
}
答案 2 :(得分:1)
result