java - 使用 javafx 的基本计算器 : how to reset or restart

标签 java javafx stack

我正在使用 JAVA FX 和堆栈制作一个基本计算器。给出输入并按“=”按钮后,我得到了结果。但是,当我尝试在获得第一个结果后输入下一个表达式时,下一个表达式会附加结果并被评估为无效(这是在我的程序中评估表达式的情况之一)。我想要的是,如果我在按前一个表达式的“=”后按任何数字按钮,它应该清除文本字段并采用下一个表达式作为输入,并在按“=”时对其进行评估。我认为我应该将“评估”部分放入循环中,但不知道该怎么做。

package application;
import java.util.*;
import java.util.Stack;

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.StageStyle;



public class Main extends Application {

/*The keyboard key values*/
private static final String[][] key_values = {
        { "7", "8", "9", "/" },
        { "4", "5", "6", "*" },
        { "1", "2", "3", "-" },
        { "0", "c", "=", "+" }
};
private Button btn[][] = new Button[4][4]; //all the keys
TextField calculator_screen;  //the calculator screen


int flag=0,repeat=0;
String exp;
String temp;
String sample = "0";
String sample2 = "0";
Double num1=0.0,num2=0.0,sum=0.0;
Double checkNum=0.0;
Double temp_sum=0.0;
Stack <String>stack = new Stack<>();
Stack <String>stack_new = new Stack<>();
//MyStack s = new MyStack();
public static void main(String[] args) 
{ 
    launch(args);
    //System.out.print("123456789");

}


@Override public void start(Stage stage) {

    /*The outside layout*/
    final VBox layout = new VBox(30); //the size vertically

    /*The inside layout for keys or buttons*/
    TilePane keypad = new TilePane(); //even it is called keypad, it is a layout
    keypad.setVgap(7);
    keypad.setHgap(7); //set the gap between keys


    /*Create Calculator Screen */
    calculator_screen =  new TextField();
    calculator_screen.setStyle("-fx-background-color: #FFFFFF;"); //set the style of the screen
    calculator_screen.setAlignment(Pos.CENTER_RIGHT); //make the screen in the center of the calculator
    calculator_screen.setEditable(false); //make sure the screen cannot be typed in manually
    calculator_screen.setPrefWidth(500); //set the windth of the screen

    /*Create Calculator keyboard*/
    keypad.setPrefColumns(key_values[0].length); //set the preferred number of columns

    for (int i = 0; i < 4; i++) 
    {
        for (int j = 0; j < 4; j++) 
        {
            btn[i][j] = new Button(key_values[i][j]);
            final int a = i;
            final int b = j;

            /*Add button event*/
            btn[i][j].setOnAction(new EventHandler<ActionEvent>(){

                @Override
                public void handle(ActionEvent event) {

                    calculator_screen.appendText(key_values[a][b]);
                    exp = calculator_screen.getText().toString();

                }

        }
                    );

            keypad.getChildren().add(btn[i][j]);
        }
    }


    btn[3][1].setOnAction(new EventHandler<ActionEvent>()
            {

                @Override
                public void handle(ActionEvent arg0) {
                    // TODO Auto-generated method stub
                    calculator_screen.setText("");
                }

            });


    //-------------When "=" button is pressed--------

    btn[3][2].setOnAction(new EventHandler<ActionEvent>()
    {

        @Override
        public void handle(ActionEvent arg0) 
        {
            // TODO Auto-generated method stub
            //System.out.println("=============");
            //System.out.println("Expression = "+ exp);


            //--------------Pushing the elements to the stack-------------------

            exp = exp+"\n";
            char [] ch = exp.toCharArray();
            int len = ch.length;
            int i=0;

            for(int j=0;j<len;j++)
            {
                if(ch[j]>='0' && ch[j]<='9')
                {
                    //System.out.println("Digit = "+ ch[j]);
                    i=j;
                    sample = "0";
                    while(ch[i]>='0' && ch[i]<='9' && i < len)//To check if there is a more than 1 digit nummber.
                    {
                        if(ch[i]>='0' && ch[i]<='9')
                        {
                            System.out.println("Digit = "+ ch[i]);
                            System.out.println("sample before = "+ sample);
                            sample = sample+exp.charAt(i);
                            System.out.println("sample after = "+ sample);
                            i++;
                        }
                    }
                    stack.push(sample);
                    //System.out.println("hiii");
                    j=i-1;
                }
                else
                {
                    System.out.println("Sign = "+ ch[i]);

                    stack.push(Character.toString(ch[i]));
                }
            }
            temp=stack.pop();
            int size= stack.size();
            System.out.println("Size of stack = "+ size);
            //if(stack.size()==null)

            //-----------Reversing the order of the stack-------------

            while(!stack.isEmpty())
            {
                sample2=stack.pop();
                stack_new.push(sample2);
            }


            //-----------Evaluating the expression--------------------

            while(!stack_new.isEmpty())
            {
                System.out.println("--------");


                temp=stack_new.peek();
                System.out.println("Stack item = "+temp);
                int type =checkString(temp) ;

                if(type == 0)
                {
                    num1 = Double.parseDouble(temp);
                    stack_new.pop();
                    //System.out.println("Stack item = "+sum);

                }
                else if(type ==5)
                {
                    System.out.println("Stack Empty");
                    //stack.pop();
                    flag=2;
                    break;
                }
                else
                {
                    int op=checkString(temp);
                    stack_new.pop();
                    //System.out.println("Stack item = "+sum);
                    temp=stack_new.peek();
                    type =checkString(temp) ;
                    if(type!=0)
                    {
                        System.out.println("Invalid");
                        flag=2;
                    }
                    else
                    {

                        num2=Double.parseDouble(temp);
                        if(op==1)
                        {
                            temp_sum=num1+num2;
                            System.out.println("Sum = "+ temp_sum);
                        }
                        else if(op==2)
                        {
                            temp_sum=num1-num2;
                            System.out.println("Diff = "+ temp_sum);
                        }
                        else if(op==3)
                        {
                            temp_sum=num1*num2;
                            System.out.println("Product = "+ temp_sum);
                        }
                        else
                        {
                            if(num2!=0)
                            {
                                temp_sum=num1/num2;
                                System.out.println("Division = "+ temp_sum);
                            }
                            else
                            {
                                System.out.println("Cannot divide by 0");
                                flag=1;
                            }
                        }
                        num1=temp_sum;
                    }
                    stack_new.pop();
                }

            }
            System.out.println("result = "+ temp_sum);
            if(flag==0)
                calculator_screen.setText(temp_sum.toString());
            else if(flag==1)
            {
                calculator_screen.setText("Error");
                calculator_screen.setStyle("-fx-text-fill: red;");

            }
            else if(flag==2)
            {
                calculator_screen.setText("Invalid Expression");
                calculator_screen.setStyle("-fx-text-fill: red;");

            }


        }

        public int checkString(String temp) {
            // TODO Auto-generated method stub

        if(temp.length()==1)
        {

            char ch=temp.charAt(0);
            if(ch=='+')
                return 1;
            else if(ch=='-')
                return 2;
            else if(ch=='*')
                return 3;
            else if(ch=='/')
                return 4;
            else 
                return 5;

        }
        else
            return 0;
        }

    });



    /*Put the calculator screen and keypad into a VBox layout*/
    layout.setAlignment(Pos.CENTER);
    //layout.setStyle("-fx-background-color: #797983; -fx-padding: 20; -fx-font-size: 20;");
    layout.getChildren().addAll(calculator_screen, keypad);
    calculator_screen.prefWidthProperty().bind(keypad.widthProperty());


    /*Show the window*/
    stage.setTitle("Calculator");
    stage.initStyle(StageStyle.UTILITY);
    stage.setResizable(false);
    Scene scene = new Scene(layout);
    scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
    stage.setScene(scene);
    stage.show();
}

}

最佳答案

我找到了您问题的解决方案。

import java.util.Stack;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.StageStyle;



public class Main extends Application {

/*The keyboard key values*/
private static final String[][] key_values = {
        { "7", "8", "9", "/" },
        { "4", "5", "6", "*" },
        { "1", "2", "3", "-" },
        { "0", "c", "=", "+" }
};
private Button btn[][] = new Button[4][4]; //all the keys
TextField calculator_screen;  //the calculator screen

boolean isEqualCalled = false;
int flag=0,repeat=0;
String exp;
String temp;
String sample = "0";
String sample2 = "0";
Double num1=0.0,num2=0.0,sum=0.0;
Double checkNum=0.0;
Double temp_sum=0.0;
Stack <String>stack = new Stack<>();
Stack <String>stack_new = new Stack<>();
//MyStack s = new MyStack();
public static void main(String[] args) 
{ 
    launch(args);
    //System.out.print("123456789");

}


@Override public void start(Stage stage) {

    /*The outside layout*/
    final VBox layout = new VBox(30); //the size vertically

    /*The inside layout for keys or buttons*/
    TilePane keypad = new TilePane(); //even it is called keypad, it is a layout
    keypad.setVgap(7);
    keypad.setHgap(7); //set the gap between keys


    /*Create Calculator Screen */
    calculator_screen =  new TextField();
    calculator_screen.setStyle("-fx-background-color: #FFFFFF;"); //set the style of the screen
    calculator_screen.setAlignment(Pos.CENTER_RIGHT); //make the screen in the center of the calculator
    calculator_screen.setEditable(false); //make sure the screen cannot be typed in manually
    calculator_screen.setPrefWidth(500); //set the windth of the screen

    /*Create Calculator keyboard*/
    keypad.setPrefColumns(key_values[0].length); //set the preferred number of columns

    for (int i = 0; i < 4; i++) 
    {
        for (int j = 0; j < 4; j++) 
        {
            btn[i][j] = new Button(key_values[i][j]);
            final int a = i;
            final int b = j;

            /*Add button event*/
            btn[i][j].setOnAction(new EventHandler<ActionEvent>(){

                @Override
                public void handle(ActionEvent event) {
                    if(isEqualCalled){
                        calculator_screen.clear();
                        isEqualCalled = false;
                    }
                    calculator_screen.appendText(key_values[a][b]);
                    exp = calculator_screen.getText().toString();

                }

        }

                    );

            keypad.getChildren().add(btn[i][j]);
        }
    }

    btn[3][1].setOnAction(new EventHandler<ActionEvent>()
            {

                @Override
                public void handle(ActionEvent arg0) {
                    // TODO Auto-generated method stub
                    calculator_screen.setText("");
                }

            });


    //-------------When "=" button is pressed--------

    btn[3][2].setOnAction(new EventHandler<ActionEvent>()
    {

        @Override
        public void handle(ActionEvent arg0) 
        {
            // TODO Auto-generated method stub
            //System.out.println("=============");
            //System.out.println("Expression = "+ exp);
            isEqualCalled = true;

            //--------------Pushing the elements to the stack-------------------
            exp = exp+"\n";
            char [] ch = exp.toCharArray();
            int len = ch.length;
            int i=0;

            for(int j=0;j<len;j++)
            {
                if(ch[j]>='0' && ch[j]<='9')
                {
                    //System.out.println("Digit = "+ ch[j]);
                    i=j;
                    sample = "0";
                    while(ch[i]>='0' && ch[i]<='9' && i < len)//To check if there is a more than 1 digit nummber.
                    {
                        if(ch[i]>='0' && ch[i]<='9')
                        {
                            System.out.println("Digit = "+ ch[i]);
                            System.out.println("sample before = "+ sample);
                            sample = sample+exp.charAt(i);
                            System.out.println("sample after = "+ sample);
                            i++;
                        }
                    }
                    stack.push(sample);
                    //System.out.println("hiii");
                    j=i-1;
                }
                else
                {
                    System.out.println("Sign = "+ ch[i]);

                    stack.push(Character.toString(ch[i]));
                }
            }
            temp=stack.pop();
            int size= stack.size();
            System.out.println("Size of stack = "+ size);
            //if(stack.size()==null)

            //-----------Reversing the order of the stack-------------

            while(!stack.isEmpty())
            {
                sample2=stack.pop();
                stack_new.push(sample2);
            }


            //-----------Evaluating the expression--------------------

            while(!stack_new.isEmpty())
            {
                System.out.println("--------");


                temp=stack_new.peek();
                System.out.println("Stack item = "+temp);
                int type =checkString(temp) ;

                if(type == 0)
                {
                    num1 = Double.parseDouble(temp);
                    stack_new.pop();
                    //System.out.println("Stack item = "+sum);

                }
                else if(type ==5)
                {
                    System.out.println("Stack Empty");
                    //stack.pop();
                    flag=2;
                    break;
                }
                else
                {
                    int op=checkString(temp);
                    stack_new.pop();
                    //System.out.println("Stack item = "+sum);
                    temp=stack_new.peek();
                    type =checkString(temp) ;
                    if(type!=0)
                    {
                        System.out.println("Invalid");
                        flag=2;
                    }
                    else
                    {

                        num2=Double.parseDouble(temp);
                        if(op==1)
                        {
                            temp_sum=num1+num2;
                            System.out.println("Sum = "+ temp_sum);
                        }
                        else if(op==2)
                        {
                            temp_sum=num1-num2;
                            System.out.println("Diff = "+ temp_sum);
                        }
                        else if(op==3)
                        {
                            temp_sum=num1*num2;
                            System.out.println("Product = "+ temp_sum);
                        }
                        else
                        {
                            if(num2!=0)
                            {
                                temp_sum=num1/num2;
                                System.out.println("Division = "+ temp_sum);
                            }
                            else
                            {
                                System.out.println("Cannot divide by 0");
                                flag=1;
                            }
                        }
                        num1=temp_sum;
                    }
                    stack_new.pop();
                }

            }
            System.out.println("result = "+ temp_sum);
            if(flag==0)
                calculator_screen.setText(temp_sum.toString());
            else if(flag==1)
            {
                calculator_screen.setText("Error");
                calculator_screen.setStyle("-fx-text-fill: red;");

            }
            else if(flag==2)
            {
                calculator_screen.setText("Invalid Expression");
                calculator_screen.setStyle("-fx-text-fill: red;");

            }


        }

        public int checkString(String temp) {
            // TODO Auto-generated method stub

        if(temp.length()==1)
        {

            char ch=temp.charAt(0);
            if(ch=='+')
                return 1;
            else if(ch=='-')
                return 2;
            else if(ch=='*')
                return 3;
            else if(ch=='/')
                return 4;
            else 
                return 5;

        }
        else
            return 0;
        }

    });



    /*Put the calculator screen and keypad into a VBox layout*/
    layout.setAlignment(Pos.CENTER);
    //layout.setStyle("-fx-background-color: #797983; -fx-padding: 20; -fx-font-size: 20;");
    layout.getChildren().addAll(calculator_screen, keypad);
    calculator_screen.prefWidthProperty().bind(keypad.widthProperty());


    /*Show the window*/
    stage.setTitle("Calculator");
    stage.initStyle(StageStyle.UTILITY);
    stage.setResizable(false);
    Scene scene = new Scene(layout);
    stage.setScene(scene);
    stage.show();
}

}

使用此代码并检查 isEqualCalled 变量并遵循。你就会明白。

关于java - 使用 javafx 的基本计算器 : how to reset or restart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35925676/

相关文章:

java - Gradle生成的Jar不包含gwt.xml文件?

java - REST api 的类级 validator 甚至不执行 validator

java - Nancy Java Web 框架

java - 如何通过更改标题(即旋转对象)来避免与边框或彼此之间的碰撞

JavaFX 不在 Java 7u40 的类路径上,oracle 文档说应该包含该类路径

Java:如何让扫描仪仅匹配第一次出现的情况,如果之前已匹配过则跳过

JavaFX:绑定(bind)和弱监听器

angular - 如何在 ionic 3 中单击设备后退按钮从选项卡 2 导航到选项卡 1

c - 协助使用C代码和汇编代码绘制堆栈

java - 如何将元素添加到链表末尾