CommandLine Java计算器

Lea*_*th2 3 java calculator

我刚刚学习了java,但是根据我从C++中获得的旧经验,我认为我可以编写一个命令行计算器,它只需要一行支持所有4个基本操作符.但我有一点问题.

这是我的代码:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的代码,但是当我运行它时它会问我计算然后给出这个错误.

Exception in thread "main" java.lang.NullPointerException
    at omg.main(omg.java:38)
Run Code Online (Sandbox Code Playgroud)

可能有更好更简单的方法,我希望听到一个更好的方法和修复我的方式.提前致谢

Hov*_*els 7

你声明:

char[] tempnum = null;
Run Code Online (Sandbox Code Playgroud)

但是你在哪里设置=非空值?因此,每当您尝试使用它时,就好像它是一个完全驱动的物体一样,您将获得一个NPE抛出.

编辑:您的代码中还有其他问题,包括在数组上调用toString(),该数组将返回数组的默认值toString - 而不是您想要的那种情况.

所以不是这样:

tempnumstr = tempnum.toString();
Run Code Online (Sandbox Code Playgroud)

你可能想要这样的东西:

tempnumstr = new String(tempnum); 
Run Code Online (Sandbox Code Playgroud)

或者可能

tempnumstr = new String(tempnum).trim(); // get rid of trailing whitespace if needed
Run Code Online (Sandbox Code Playgroud)

编辑2:您的程序中似乎有两个char数组,tempnum和testchar,一个用字符填充,另一个不用.他们俩的目的是什么?考虑使用一些注释来编写代码,这样我们就能更好地理解它并且能够更好地帮助您.


mer*_*ike 6

Hovercraft Full Of Eels已经向你指出了NullPointerException.除此之外的原因,我看到你的代码中可以改进的一些东西.这是我如何做到的:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,扫描程序假定操作员之前和之后都有空格.

示例输出:

Please enter your calculation
1 + 2
3
Run Code Online (Sandbox Code Playgroud)

细节上的改进:

  1. 可以在首次使用变量时声明变量.在Java中习惯于利用它(更短的代码大小,不需要重复变量名称.)
  2. Scanner除了读取整行之外,还提供标记化.无需重新发明轮子.
  3. char(可以是整数类型)switch.

  • 不错的1+.只有一个小的建议,我讨厌甚至提到:处理完资源后处理资源总是一个好习惯,这包括Scanner对象,当你使用它时应该关闭它.这真的不会使这个程序受益,这就是为什么我不想提及它,但这是一个很好的习惯,因为有时它会*无关紧要.:) (2认同)