Reputation: 75
First of all it's my first app, I'm trying to code a calculator. When pressing an operator, if there is old one, calculate it and send the result to continue with it to the new process. The calculation process don't go to the second step, anyone can help to make this code work properly?
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class main extends Application {
String num1 ="";
String num2 ="";
String op ;
double result= 0;
boolean oldop =false ;
// the GUI component
public void start(Stage stage) throws Exception {
Button one = new Button("1");
Button two = new Button("2");
Button pls = new Button("+");
Button eql = new Button("=");
Button ac = new Button("AC");
Label lbl = new Label("empty");
FlowPane pane = new FlowPane();
pane.setHgap(10);
pane.getChildren().addAll(one,two,pls,eql,ac,lbl);
Scene scene = new Scene(pane);
stage.setScene(scene);
stage.show();
// The Actions on buttons
one.setOnAction(e ->
{
if(!oldop){
num1+='1';
lbl.setText(num1);}
else {
num2+='1';
lbl.setText(num2);}});
two.setOnAction(e ->
{
if(!oldop){
num1+='2';
lbl.setText(num1);}
else {
num2+='2';
lbl.setText(num2);}});
pls.setOnAction(e -> {
if(!oldop){
oldop = true;
op="+";
lbl.setText(op);}
else {
result=calc(num1 , num2 ,op);
num1=String.valueOf(result);
num2="";
op="+";
lbl.setText(num1+op);
oldop = true;}});
eql.setOnAction(e ->{
if(oldop){
result=calc(num1 , num2 , op);
lbl.setText(String.valueOf(result));
oldop=false;
num2="";}
else
return;});
ac.setOnAction(e -> {
num1="";
num2="";
result=0;
oldop=false;});
}
// The calculation method
public int calc (String n1 , String n2 , String op){
switch (op) {
case "+" :
return Integer.parseInt(n1) + Integer.parseInt(n2) ;
case "-" :
return Integer.parseInt(n1) - Integer.parseInt(n2) ;
case "*" :
return Integer.parseInt(n1) * Integer.parseInt(n2) ;
case "/" :
return Integer.parseInt(n1) / Integer.parseInt(n2) ;
default :
return 0;
}
}
public static void main(String[] args) {
Application.launch(args);
}
}
Upvotes: 0
Views: 8976
Reputation: 27373
The problem seems to be that you cannot use the result of an previous operation in the second step, because you use String.valueOf
which gives e.g. 3.0 for the int 3 (result of 1+2). This string cannot be used again in calc
as it cannot be parsed back to an int with `Integer.parseInt.
I would suggest to work with int
and only convert them to strings for the labels.
An ulgy workaround would be to add the following lines at the beginning of calc
:
n1=n1.split("\\.")[0];
n2=n2.split("\\.")[0];
Upvotes: 1