2016-04-01 112 views
0

まず第一に、それは私の最初のアプリです、私は電卓をコーディングしようとしています。オペレータを押すときに古いものがある場合は、それを計算し、結果を送信して新しいプロセスに進みます。計算プロセスは2番目のステップには進まず、誰でもこのコードを正しく動作させることができますか?シンプルな基本的な電卓Javafx

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); 
} 
} 
+0

おそらく、この[簡単な計算例](https://gist.github.com/jewelsea/4344564)役立つかもしれません君は。 – jewelsea

答えて

0

問題は、あなたがString.valueOfを使用するので、あなたが例えば与える、第2工程では、前の操作の結果を使用できないことのようですint 3の場合は3.0です(1 + 2の結果)。 calcでこの文字列を再び使用することはできません。これは `Integer.parseInt 'でintに解析できないためです。

私はintで作業し、ラベルの文字列に変換することをお勧めします。

ulgy回避策はcalcの先頭に以下の行を追加することです:

n1=n1.split("\\.")[0]; 
    n2=n2.split("\\.")[0]; 
+0

それは仕事です、おかげで多くの助け:) 私は本当に感謝している^ _ ^ –

関連する問題