我正在尝试制作一个小而简单的应用程序,询问基本的数学问题,并等待用户输入检查并输出“正确”或“不正确”。我到达的问题是按下按钮时激活检查过程。有时代码会运行并执行除了运行检查过程之外的所有操作,但是我也遇到了一个问题,即代码卡在循环中而不会加载。
import java.util.Random;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.stage.Stage;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
public class Main extends Application
{
final Button enterbutton = new Button("Enter");
int ans = 0;
final ListView<String> console = new ListView<String>(FXCollections.<String>observableArrayList());
final TextField textbox = new TextField();
public int init(Stage firstStage)
{
Group root = new Group();
firstStage.setScene(new Scene (root));
VBox box = new VBox(10);
int firstNumber = 0, secondNumber = 0, answer = 0, signNumber = 0, count = 0;
Random rnd1 = new Random();
Random rnd2 = new Random();
Random rnd3 = new Random();
firstNumber = rnd1.nextInt(100);
secondNumber = rnd2.nextInt(100);
signNumber = rnd3.nextInt(3);
console.getItems().addListener(new ListChangeListener<String>()
{
public void onChanged(Change<? extends String> change)
{
while (change.next())
{
if (change.getList().size() > 10)
{
change.getList().remove(0);
}
}
}
});
answer = Question(firstNumber, secondNumber, signNumber, count);
console.getItems().add(firstNumber + " " + secondNumber + " " + signNumber);
console.getItems().add(answer + " ");
box.getChildren().addAll(textbox, enterbutton, console);
root.getChildren().add(box);
return answer;
}
@Override
public void start(Stage primaryStage) throws Exception
{
int guessCounter = 0;
init(primaryStage);
primaryStage.show();
}
public int Question (int num1, int num2, int num3, int counter)
{
while (counter == 0)
{
switch(num3)
{
case 0:
ans = num1 + num2;
break;
case 1:
ans = num1 - num2;
break;
case 2:
ans = num1 * num2;
break;
default:
ans = 0;
break;
}
counter = 1;
}
return ans;
}
public boolean GuessCheck()
{
int userInput = 0, actualAnswer = 0;
actualAnswer = ans;
if (enterbutton.isPressed())
{
userInput = Integer.parseInt(textbox.toString());
if (userInput == actualAnswer)
{
console.getItems().add("Correct");
}
else if (userInput != actualAnswer)
{
console.getItems().add("Incorrect");
}
}
return true;
}
public void main(String[] args)
{
launch(args);
}
}