【发布时间】:2011-10-31 13:40:02
【问题描述】:
我刚刚学习了 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
}
}
这是我的代码,但是当我运行它时,它会询问我的计算,然后给出这个错误。
Exception in thread "main" java.lang.NullPointerException
at omg.main(omg.java:38)
可能有更好、更简单的方法来做这件事,我想听听更好的方法和我的方法的修复。提前致谢
【问题讨论】:
-
你的 C(++) 习惯是可见的。 Java 中的类应该以大写字母开头。变量中的每个单词也应以大写字母开头(例如:machineCode)。并且变量通常在且仅在使用时才被声明和初始化。并非所有方法的开头。 machineCode 应该是一个枚举而不是一个 int。
-
在本论坛的第二篇文章中很好地使用了带有适当代码缩进的格式化代码!
标签: java calculator