我剛剛學過java,但是從我從C++學來的舊經驗,我想我可以編寫一個命令行計算器,它只需一行支持所有4個基本操作符。但我有一些問題。CommandLine Java計算器
這是我的代碼:
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。 –
只有在你的第二篇文章中有正確代碼縮進的格式化代碼才能使用! –