【问题标题】:Trying to implement a score system while using if/else. [JAVA]尝试在使用 if/else 时实现评分系统。 [JAVA]
【发布时间】:2014-06-09 00:43:03
【问题描述】:

我是 java 的初学者,我正在尝试使用我的 if/else 语句根据正确或错误答案递增或递减的评分系统。如果用户匹配在文本文件中找到的文本,程序应该增加,如果不正确,程序应该减少。现在,如果不正确,程序将显示“-1”,如果正确,则显示“1”,无论它通过循环多少次。它应该改变结果的值,但它一直重置为“0”。我已经尝试过了,但我相信我的范围有问题。如果有人可以提供帮助,我将不胜感激。

package typetrain;
import java.util.*;
import java.io.*;
import javax.swing.*;

/**
 *
 * @author Haf
  */
public class Game1 {
public void Game () {

    JOptionPane.showMessageDialog(null, "Please answer in the correct line of text. \n"  +
            "each line of text will grant you one point. "
            + "\nIncorrect answers will lead to a point being subtracted");
    String fileName = "test.txt";
    String line;
    ArrayList aList = new ArrayList();

    try {
        BufferedReader input = new BufferedReader (new FileReader(fileName));
        if (!input.ready())   {
            throw new IOException();

        }

        while ((line = input.readLine()) !=null) {
            aList.add(line);
        }
        input.close();
    } catch (IOException e) {
        System.out.println(e);

    }

    int sz = aList.size();


    for (int i = 0; i< sz; i++) {


        int result = 0;
        String correctAnswer = aList.get(i).toString();
        String userAnswer = JOptionPane.showInputDialog(null, "Copy this line of text! \n" + aList.get(i).toString());


        if (correctAnswer.equals(userAnswer)) {
            JOptionPane.showMessageDialog(null, "Correct!");
            result++;


        }

        else if (!correctAnswer.equals(userAnswer)) {
                    JOptionPane.showMessageDialog(null, "Incorrect!");
                    result--;

        }                  

        JOptionPane.showMessageDialog(null, result);
    }

} }

【问题讨论】:

  • 请指明问题所在的行。
  • @MouseEvent 我想如果他知道的话,他就不会在这里发帖了。
  • 对不起,我很含糊。问题已经解决了,谢谢。

标签: java if-statement scope


【解决方案1】:

您只需将 int result = 0; 移动到 for 循环之前的行。否则每次都会重置为0。

【讨论】:

  • 啊,非常感谢,它有效。我相信我试过了,但当时我可能遇到了另一个错误。
  • 很高兴为您提供帮助!继续并将其标记为已回答,以便每个人都知道您的问题已解决。
猜你喜欢
  • 1970-01-01
  • 2017-06-23
  • 2019-08-08
  • 1970-01-01
  • 1970-01-01
  • 2013-09-02
  • 1970-01-01
  • 1970-01-01
  • 2012-07-05
相关资源
最近更新 更多