Question

I'm a beginner at java and I'm trying to have a score system that uses my if/else statements to either increment or decrement according to right or wrong answers. The program should increment if the user matches the text that is found in the text file and decrement if incorrect. Right now, the program will display "-1" if incorrect and "1" if correct, regardless of how many times it goes through the loop. It should change the value of result but it keeps resetting to "0". I have tried already but I believe I had an issue with scope. If anyone could help I'd be very grateful.

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);
    }

} }

Was it helpful?

Solution

You just need to move your int result = 0; to the line before your for loop. Otherwise, it will get reset to 0 each time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top