问题
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.
This is my code:
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
回答1:
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.
Example output:
Please enter your calculation
1 + 2
3
The improvements in detail:
- 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.)
Scanner
provides tokenizing in addition to reading the entire line. No need to reinvent the wheel.char
(being an integer type) can beswitch
ed on.
回答2:
You declare:
char[] tempnum = null;
But where do you set it = to a non-null value? So any time you try to use it as if it were a fully actuated object, you'll get a NPE thrown.
Edit: there are other issues in your code including calling toString() on an array which will return array's default toString -- not what you want in that situation.
So rather than this:
tempnumstr = tempnum.toString();
You probably want something like this:
tempnumstr = new String(tempnum);
or possibly
tempnumstr = new String(tempnum).trim(); // get rid of trailing whitespace if needed
Edit 2: You appear to have two char arrays in your program, tempnum and testchar, one that you fill with chars and one you don't. What is the purpose of both of them? Consider peppering your code with some comments too so we can understand it better and better be able to help you.
回答3:
Your problem is this line:
tempnum[t] = testchar[t];
Which will throw a NullPointerException as you previously declared it as null: char[] tempnum = null;
You need to change it to char[] tempnum = new char[size];
which will initialise it to an empty array to hold type char
. Where size
is any integer.
回答4:
char[] tempnum = null;
should be set to something like
char[] tempnum = new char[4];
basically it is null when used at line 38.
回答5:
On line 38 you try to acces the variable tempnum
which is initialized to null
you have to initialize the variable tempnum like this:
tempnum = new char[n]
where n will be the length of the array
回答6:
You forgot to allocate tempNum
which results in a NUllPointerException
when you try to use it in an array context.
char[].toString()
won't do what you expect (it returns a hashcode for the array object), to create a string using the contents of the array use new String(char[])
.
回答7:
First of all, it error at this line: tempnum[t] = testchar[t];
Reason: tempnum
have not point to any thing (null)
Fix: tempnum = testchar;
or tempnum = new char[testchar.length]
来源:https://stackoverflow.com/questions/7138038/commandline-java-calculator