首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用javafx的基本计算器:如何重置或重新启动

使用javafx的基本计算器:如何重置或重新启动
EN

Stack Overflow用户
提问于 2016-03-11 03:37:53
回答 2查看 1.6K关注 0票数 1

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

代码语言:javascript
复制
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();
}

}
EN

回答 2

Stack Overflow用户

发布于 2016-03-11 14:49:46

我找到了你问题的答案。

代码语言:javascript
复制
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变量,然后执行以下操作。你会明白的。

票数 0
EN

Stack Overflow用户

发布于 2018-10-15 09:12:38

如果要清除JTextField (或JTextArea),只需将以下行插入到按钮操作中:

代码语言:javascript
复制
yourTextFieldVariable.setText(null);

这将在单击带线的按钮时清除该变量的字段。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35925676

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档