我正在使用JAVA FX和堆栈制作一个基本的计算器。提供输入并按下“ =”按钮后,我得到了结果。但是,当我尝试在获得第一个结果后立即输入下一个表达式时,下一个表达式将与结果相加并被评估为INVALID(这是在我的程序中评估该表达式的一种情况)。我想要的是,如果我在对上一个表达式按“ =”之后按任意数字按钮,则应清除TextField并接受下一个表达式作为输入,并在按“ =”时对其求值。我认为我应该将“评估”部分放在一个循环中,但无法弄清楚该怎么做。
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的基本计算器:如何重置或重新启动,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35925676/