命令行Java计算器 [英] CommandLine Java Calculator

查看:56
本文介绍了命令行Java计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚学过Java,但是根据我从C ++中学到的经验,我坚信我可以编写一个命令行计算器,仅用一行就可以支持所有4种基本运算符。但是我有点问题。

I've just learned java but from my old experience coming from C++ i tought that i can write a commandline calculator wich supports all 4 basic operators with just one line. But i am having a bit of problem.

这是我的代码:

import java.util.Scanner;

public class omg {
    public static void main(String args[]) {
        int fnum,snum,anum = 0;
        String strtype; //The original calculation as string
        char[] testchar; //Calculation as chararray
        char currentchar; //current char in the char array for the loop
        int machinecode = 0; //Operator converted to integer manually
        String tempnumstr; //first and second numbers temp str to be converted int
        int operatorloc = 0; //operator location when found
        char[] tempnum = new char[256];
        Scanner scan = new Scanner(System.in); // The scanner obviously
        System.out.println("Enter The Calculation: ");
        strtype = scan.nextLine();
        testchar = strtype.toCharArray(); //converting to char array
        for(int b = 0; b < testchar.length; b++) //operator locating
        {
            currentchar = testchar[b];
            if(currentchar == '+') {
                machinecode = 1;
                operatorloc = b;
            }
            else if(currentchar == '-') {
                machinecode = 2;
                operatorloc = b;
            }
            else if(currentchar == '*') {
                machinecode = 3;
                operatorloc = b;
            }
            else if(currentchar == '/') {
                machinecode = 4;
                operatorloc = b;
            }
        }
        for(int t = 0;t < operatorloc;t++) { //transferring the left side to char
            tempnum[t] = testchar[t];
        }
            tempnumstr = tempnum.toString(); //converting char to string
            fnum = Integer.parseInt(tempnumstr); //parsing the string to a int
        for(int temp = operatorloc;temp < testchar.length;temp++) { //right side
            for(int t = 0;t<(testchar.length-operatorloc);t++) {
                tempnum[t] = testchar[temp];
            }
        }
        tempnumstr = tempnum.toString(); //converting to char
        snum = Integer.parseInt(tempnumstr); //converting to int
        switch(machinecode) { //checking the math to be done
        case 1:
            anum = fnum + snum;
            break;
        case 2:
            anum = fnum - snum;
            break;
        case 3:
            anum = fnum * snum;
            break;
        case 4:
            anum = fnum / snum;
        }
        System.out.println(anum); //printing the result
    }
}

这是我的代码,但是当我运行它会问我计算结果,然后给出此错误。

This is my code but when i run it it will ask me the calculation and then give this error.

Exception in thread "main" java.lang.NullPointerException
    at omg.main(omg.java:38)

可能会有更好的选择这样做更简单,我想同时听到一种更好的方法和一种解决方法。预先感谢

There might be a better and easier way of doing this i would like to hear both a better way and a fix for my way. Thanks in advance

推荐答案

气垫船充满鳗鱼已经向您指出了 NullPointerException的原因。 / code>除此之外,我发现您的代码中还有很多可以改进的地方。我的操作方法如下:

Hovercraft Full Of Eels has already pointed you to the reason for the NullPointerException. In addition to that, I see quite a few things that could be improved in your code. Here's how I'd do it:

import java.util.Scanner;

public class SimpleCalculator {

    public static void main(String[] args) {
        System.out.println("Please enter your calculation");
        Scanner scanner = new Scanner(System.in);
        int left = scanner.nextInt();
        String op = scanner.next();
        int right = scanner.nextInt();
        System.out.println(compute(left, op, right));
    }

    private static int compute(int left, String op, int right) {
        switch (op.charAt(0)) {
        case '+':
            return left + right;
        case '-':
            return left - right;
        case '*':
            return left * right;
        case '/':
            return left / right;
        }
        throw new IllegalArgumentException("Unknown operator:" + op);
    }
}

请注意,扫描仪假定前后都有空白

Note that the Scanner assumes there is whitespace before and after the operator.

示例输出:

Please enter your calculation
1 + 2
3

详细的改进:


  1. 变量可能在您第一次使用它们的地方声明。 Java习惯于利用它(较短的代码大小,无需重复变量名。)

  2. Scanner 提供除了读取整行外,还进行标记化。

  3. char (是整数类型)可以通过开关开始。

  1. Variables may be declared where you first use them. It is customary in Java to take advantage of that (shorter code size, no need to repeat the variable name.)
  2. Scanner provides tokenizing in addition to reading the entire line. No need to reinvent the wheel.
  3. char (being an integer type) can be switched on.

这篇关于命令行Java计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆