题目解析
给定一组数 以及 对应的符号
请你计算出最后的答案
解题思路
使用列表来实现依次获取数据
计算按照题目要求计算 n2 op n1的答案即可
计算的时候 需要特意去查看 / 的情况
需要判断除数是否为0
代码
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args) throws IOException
{
LinkedList<Integer> shu = new LinkedList<Integer>(); // 存储数字
LinkedList<String> op = new LinkedList<String>(); // 存储运算符
int n = sc.nextInt();
for (int i = 1; i <= n; i++)
shu.push(sc.nextInt());
for (int i = 1; i < n; i++)
op.push(sc.next());
// 判断是否整数0了
boolean f = false;
// 需要先取出第一个数
int n1 = shu.pollFirst();
while (op.size() != 0)
{
int n2 = shu.pollFirst(); // 取出最前面的数
String s = op.pollFirst(); // 取出最前面的符号
// 题目要求为:n2 op n1
if (s.equals("+"))
n1 = n2 + n1;
else if (s.equals("-"))
n1 = n2 - n1;
else if (s.equals("*"))
n1 = n2 * n1;
else if (s.equals("/"))
{
// 判断除数是否为0
if (n1 == 0)
{
// 将被除数赋值给n1
n1 = n2;
f = true;
break;
}
n1 = n2 / n1;
}
}
out.println(f ? "ERROR: " + n1 + "/0" : n1);
out.flush();
out.close();
}
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
}