gpt4 book ai didi

java - 在另一个 if 语句中使用 if 语句的结果

转载 作者:行者123 更新时间:2023-12-01 18:02:32 24 4
gpt4 key购买 nike

我正在编写一个测验应用程序,当你回答正确的问题时你会得到分数并且你的分数会增加,我必须使用 if 语句。请有人知道如何在另一个 if 语句中使用 if 语句中的值!我对此有点困惑,它让我在这里工作......感谢您的帮助!...这是一个小代码示例;

     int x = 3;
String xy = Integer.toString(x);
int y = 0;
String yy = Integer.toString(y);

JButton one = new JButton ("Quest 1");
one.addActionListener (new ActionListener (){
public void actionPerformed(ActionEvent p) {
JFrame ex = new JFrame ();
ex.setTitle("Question 1);
ex.setSize(400, 400);
ex.setLayout(new FlowLayout());
ex.setBackground(Color.WHITE);

JLabel ey = new JLabel ("What is the capital of Japan?);
Font tan = new Font ("Script MT Bold", Font.BOLD, 18);
ey.setFont(tan);
ey.setForeground(Color.BLACK);
ex.add(ey, BorderLayout.NORTH);

JButton answ = new JButton("submit");

JTextField g = new JTextField (10);
g.setFont(tan);

String ans = "Tokyo";

String merit = "Correct";
String flop = "wrong";
String mer = merit + ans;
String flip = flop + ans;
answ.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent p) {

if (g.getText.equals("Tokyo") {
JOptionPane.showMessageDialog(null, mer);
one.setText(xy);
}
else {
JOptionPane.showMessageDialog(null,flip);
one.setText(yy);
}

//In my next Action Listener, I would love to
//pick the score from the previous listener....and add to the next score....
//So that we have something like ....
//x(updated from previous listener) + x
ex.add(g, BorderLayout.SOUTH);
}
});
}
});

最佳答案

我在提供的代码中可以猜测的唯一问题是,您正在测试 JTextField 的文本是否在 GUI 创建代码中包含特定的字符串“Tokyo”。这是在 GUI 创建时、用户有机会输入数据之前运行的代码。为了解决这个问题,if 测试应该在某个监听器中,也许是 JButton 的 ActionListener。否则我不知道你所说的 if 中的 if 是什么意思。

<小时/>

编辑

关于您的新信息:

I am writing a quiz app, where you get marks as you answer the correct questions and your score increases, and I have to use if statements.

当您在 GUI 中对代码逻辑进行硬编码时,您需要完全重新设计代码,这会导致程序非常僵化、庞大且难以增强(因为您找出),因为代码逻辑必须随着程序状态的变化而变化。

相反,您应该将程序逻辑、GUI 中的“模型”、“ View ”分离出来,并尝试创建它们并独立测试它们,类似于(或等于)“模型- View - Controller ” ”或“MVC”程序设计。从模型(程序的“核心”)开始,创建您的非 GUI Question 类,其中包含实例字段、方法和任何其他支持类。一旦经过测试和调试,然后尝试创建一个可以使用该模型并显示其状态的 GUI 或 View 类。您可能还想创建一个带有监听器的“Controller”类,以帮助将 View 连接到模型。

例如,如果您的测验是多项选择类型的程序,那么请考虑:

  • 一个 Question 类,包含问题字符串、可能的答案字符串和正确答案字符串。
  • 给它一个public boolean test(String testString),如果将正确的答案字符串传递给它,则返回 true。
  • 允许 Question 类随机化可能答案字符串的顺序,可能保存在 ArrayList 中。
  • 然后创建一个包含问题 ArrayList 的 Quiz 类。

然后创建一个 GUI 来显示这些。

  • 我通常创建用于创建 JPanel 的 GUI,而不是 JFrame,以提高灵 active ,然后在需要时创建 JFrame。
  • 创建一个 QuestionPanel,显示问题字符串和随机的可能答案字符串。
  • 将可能的答案显示为 JRadioButton,并使用 ButtonGroup 将选择限制为一个。
  • 等等......

您还需要一个类从文本文件中读取每个问题的数据,并将该数据加载到 Quiz 类中。

您还需要一个评分机制。

关于java - 在另一个 if 语句中使用 if 语句的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39679139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com