我是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);
}
} }
答案 0 :(得分:1)
您只需将int result = 0;
移至for循环前的行。否则,每次都会重置为0。