历届试题 小计算器

代码展示(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();
	}
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值