命令行Java计算器

3

我刚学了Java,但是由于我的C++经验,我认为我可以只用一行代码编写支持所有四个基本运算符的命令行计算器。但是我遇到了一些问题。

这是我的代码:

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
    }
}

这是我的代码,但运行时会询问我计算,并导致出现此错误。
Exception in thread "main" java.lang.NullPointerException
    at omg.main(omg.java:38)

可能有一种更好、更简单的方法来做这件事。我想听到更好的方法和关于我的方法的修正。提前感谢。


2
你的C(++)编程习惯是可见的。Java中的类名应该以大写字母开头。变量中的每个单词也应该以大写字母开头(例如:machineCode)。变量通常在使用时才声明和初始化,而不是在方法开始时全部声明。machineCode 应该是一个枚举类型而不是 int 类型。 - JB Nizet
1
在你在这个论坛上的第二篇帖子中,很好地使用了格式化代码和适当的缩进! - Hovercraft Full Of Eels
7个回答

7
你需要声明:
char[] tempnum = null;

但是你在哪里将它设置为非空值?因此,任何时候你试图像使用完全激活的对象一样使用它,都会抛出NPE。
编辑:您的代码中还存在其他问题,包括调用数组的toString(),这将返回数组的默认toString -- 这不是您想要的情况。
所以,与其这样:
tempnumstr = tempnum.toString();

你可能需要这样的内容:
tempnumstr = new String(tempnum); 

或者可能。
tempnumstr = new String(tempnum).trim(); // get rid of trailing whitespace if needed

编辑2:您的程序中似乎有两个char数组,tempnum和testchar,一个填充了字符,另一个没有。这两个数组的目的是什么?考虑在代码中添加一些注释,以便我们更好地理解它并能够更好地帮助您。


我已经修复了NPE并对我的代码进行了注释,但现在出现了“at java.lang.Integer.parseInt(Unknown Source)”的错误。 - Learath2
@Leararth2:你遇到了一个新问题,我们需要看到你的更新代码。由于这与原始问题无关,并且为了保持清洁,最好在SO上提出一个新问题来询问。 - Hovercraft Full Of Eels

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);
    }
}

请注意,Scanner假定运算符前后有空格。
示例输出:
Please enter your calculation
1 + 2
3

详细的改进:

  1. 可以在首次使用变量时声明变量。在Java中,这是常规做法(代码长度更短,不需要重复变量名)。
  2. Scanner提供分词功能,除了读取整行还可以进行分词。不需要重新发明轮子。
  3. char(作为一种整数类型)可以用于switch语句。

2
不错的代码!只有一个小建议,虽然我不太想提出来:当你使用完资源后,最好习惯性地将其释放,包括 Scanner 对象,应该在使用完毕后关闭。虽然这对于这个程序并没有什么实际好处,但这是一个好习惯,因为有时候它确实很重要。 :) - Hovercraft Full Of Eels
你的方法非常好,但我还在学习Java :)。我只是想以这种方式尝试一下。 - Learath2

2

你的问题出在这一行:

tempnum[t] = testchar[t];

由于之前你将其声明为null,因此会抛出NullPointerException:char[] tempnum = null;

你需要将其改为char[] tempnum = new char[size];,这将初始化为空数组以容纳类型char。其中size是任何整数。


1
char[] tempnum = null;

应该设置为类似于

char[] tempnum = new char[4];

基本上在第38行使用时它是空的。


0
在第38行,您尝试访问变量tempnum,该变量被初始化为null,您必须像这样初始化变量tempnum: tempnum = new char[n] 其中n将是数组的长度。

0
你忘记分配 `tempNum` 导致在数组上下文中使用它时出现了一个 `NUllPointerException` 。
`char[].toString()` 不会按照你的预期执行(它返回数组对象的哈希码),如果要使用数组的内容创建字符串,请使用 `new String(char[])`。

0
首先,它在这一行出错:tempnum[t] = testchar[t]; 原因: tempnum 没有指向任何东西(null) 修复方法: tempnum = testchar; 或者 tempnum = new char[testchar.length]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接