【问题标题】:Java score is not increasing with if statementsJava 分数不会随着 if 语句的增加而增加
【发布时间】:2021-05-31 01:18:06
【问题描述】:

对于我的java琐事游戏,我在开头设置了问题,例如

if(command.equals("question 1"))
    {
        txtAnswer.setText("");
        q1 = true;
        btnQ1.setEnabled(false);
        lblQuestion.setText("What is 2 + 2?");
        lblOutcome.setText("");
    }

        

然后在所有问题的“如果”之后,我有代码可以验证它是否正确,如果正确,我会增加分数。这是我使用的代码:

if(command.equals("Check")&& (txtAnswer.getText().equalsIgnoreCase("4") && (q1)))
        {
            q1= false;
            lblOutcome.setText("Correct");
            score = score +1;
            lblScore.setText("Current Score: " + score);
            
        }
        else if(command.equals("Check")&& (!txtAnswer.getText().equalsIgnoreCase("4") && (q1)))
        {
            q1= false;
            lblOutcome.setText("Incorrect");
            lblScore.setText("Current Score: " + score);
        
        }
        
        
        
        if(command.equals("Check")&& (txtAnswer.getText().equalsIgnoreCase("8") && (q2)))
        {
            q2= false;
            lblOutcome.setText("Correct");
            score = score +1;
            lblScore.setText("Current Score: " + score);
            
        }
        else if(command.equals("Check")&& (!txtAnswer.getText().equalsIgnoreCase("8") && (q2))
        {
            q2= false;
            lblOutcome.setText("Incorrect");
            lblScore.setText("Current Score: " + score);
            
        }
        

但我现在遇到的问题是分数没有增加,它只是在每个问题后完全重置为 0,所以如果我所有问题都正确,分数保持在 1。我想知道我有什么如何解决这个问题?

编辑:这是写代码的地方

private static class ButtonHandler implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        String command = e.getActionCommand();
        int score = 0;

【问题讨论】:

  • 答案取决于score 变量的声明位置,您没有显示。
  • @Eran 抱歉,我刚刚编辑了!
  • @gino,你在哪里声明了所有的“如果”?

标签: java if-statement counter


【解决方案1】:

正如我所见,您正在操作处理程序中初始化 score 变量。因此,它每次都会被删除并重新创建。

尝试将其声明为类字段:

private static class ButtonHandler implements ActionListener
{
    private int score = 0; 
    public void actionPerformed(ActionEvent e)
    {
        String command = e.getActionCommand();
        // int score = 0;  <== remove it from here

【讨论】:

  • 啊!!我懂了!非常感谢它现在有效! (抱歉,我的帐户真的很新,我试图投票,但由于我不到 15 天,它不会显示)
  • @gino 不要担心代表。这只是一个数字。很高兴我的回答对你有所帮助。欢迎使用 StackOverflow!
猜你喜欢
  • 1970-01-01
  • 2020-08-10
  • 1970-01-01
  • 2018-01-29
  • 2017-09-02
  • 1970-01-01
  • 2014-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多