历届试题 小计算器
作者:互联网
代码展示(java版)
思路分析:
- 根据指令,转换当前进制,任意进制的转换java有直接的api调用即可
- 定义基数num,如果是第一个数将输入的数字赋值给基数,方便后面运算
- 遇到初始化则将当前基数制令
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
while(bufferedReader.ready()) {
int n = Integer.parseInt(bufferedReader.readLine());
long num = 0;
int calcFlag = 1, dec = 10;
for (int i=1; i<=n; i++) {
String inst = bufferedReader.readLine();
if(inst.contains("NUM")) {
String[] x = inst.split(" ");
String numstr = x[1];
long temp = Long.valueOf(numstr, dec);
switch (calcFlag) {
case 1:
num += temp;
break;
case 2:
num -= temp;
break;
case 3:
num *= temp;
break;
case 4:
num /= temp;
break;
case 5:
num %= temp;
break;
case 0:
num = temp;
default:
break;
}
} else if(inst.contains("ADD")){
calcFlag = 1;
} else if(inst.contains("SUB")){
calcFlag = 2;
} else if(inst.contains("MUL")){
calcFlag = 3;
} else if(inst.contains("DIV")){
calcFlag = 4;
} else if(inst.contains("MOD")){
calcFlag = 5;
} else if(inst.contains("CLEAR")){
num = 0;
calcFlag = 0;
} else if(inst.contains("CHANGE")){
String[] x = inst.split(" ");
dec = Integer.parseInt(x[1]);
} else if(inst.contains("EQUAL")){
String res = Long.toString(num, dec).toUpperCase();
System.out.println(res);
}
}
}
bufferedReader.close();
}
}
标签:java,试题,int,BufferedReader,bufferedReader,io,计算器,import,历届 来源: https://blog.csdn.net/qq_40789105/article/details/88760945