I am trying to learn android development from the beginning here. So basically it will be a calculator. The way I code the calculate function is down below:
private boolean action = false;
private String fNum;
private String sNum;
private String preOp = "=";
Action as the flag to check if there is any previous option exist. fNum and sNum as the number needs to be taken care of. fNum is the one before calculate symbol button was clicked , sNum as the number after the symbol button was clicked. preOp as the storage for the last operation.
private double Calculate(String fn, String sn){
switch (preOp) {
case "plus":
return Double.parseDouble(fn) + Double.parseDouble(sn);
case "minus":
return Double.parseDouble(fn) - Double.parseDouble(sn);
case "multiply":
return Double.parseDouble(fn) * Double.parseDouble(sn);
case "device":
return Double.parseDouble(fn) / Double.parseDouble(sn);
case "=":
return Double.parseDouble(sn);
default:
return 0;
}
}
Function to actually run the calculate.
case R.id.buttonPlus:{
if(action){
fNum = text.getText().toString();
text.setText("0");
preOp = "plus";
action = true;
}
else if (!action){
sNum = text.getText().toString();
text.setText(String.valueOf(Calculate(fNum, sNum)));
preOp = "plus";
}
}break;
case R.id.buttonE:{
if(action){
sNum = text.getText().toString();
text.setText(String.valueOf(Calculate(fNum, sNum)));
preOp = "=";
}
}break;
The button functions.
So I have got the error when I clicked the + button:
12-04 05:53:04.198 31194-31194/tian.secondproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: tian.secondproject, PID: 31194
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference
at java.lang.StringToReal.parseDouble(StringToReal.java:263)
at java.lang.Double.parseDouble(Double.java:301)
at tian.secondproject.MainActivity.Calculate(MainActivity.java:21)
at tian.secondproject.MainActivity.onClick(MainActivity.java:226)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
So, am I doing it with a wrong method? or there is just some simple mistake I have made?
Thank you :)