简体   繁体   中英

Looping with arrays in java

I'm trying to write this code using mostly arrays. I'm trying to get "Correct" or "Incorrect" to display after each question and to get a total of correct/incorrect answers at the end. The goal is to use arrays to accomplish this, but I can't figure out how to use the array to display correct/incorrect after each question.

//Declarations
String rightAnswer[] = { "B", "C", "A" };
String userAnswer[] = new String [3];
String answer;
int counter;
int finalInt = 3;
int index = 0;
int correct = 0;
int incorrect = 0;

// detailedLoop
for(index = 0; index < finalInt; index++) {
    do {
        answer = JOptionPane.showInputDialog("What planet has the largest rings? \n\nA. Neptune \nB. Saturn \nC. Jupiter");
        userAnswer[index] = answer;
    } while(!(answer.equals("A")|| answer.equals("B") || answer.equals("C")));

    index++;
    do {    
        answer = JOptionPane.showInputDialog("What planet has a large redspot? \n\nA. Neptune \nB. Saturn \nC. Jupiter");
        userAnswer[index] = answer; 
    } while(!(answer.equals("A")|| answer.equals("B") || answer.equals("C")));

    index++;
    do {
        answer = JOptionPane.showInputDialog("What planet is farthest from the sun? \n\nA. Neptune \nB. Saturn \nC. Jupiter");
        userAnswer[index] = answer;
    } while(!(answer.equals("A")|| answer.equals("B") || answer.equals("C")));

    if(userAnswer[index].equals(rightAnswer[index])) {
        System.out.println("Correct!");
        correct++;
        index++;
    }
    if(!(userAnswer[index].equals(rightAnswer[index]))) {
        System.out.println("Incorrect. The right answer is " + rightAnswer[index] + ".");
        incorrect++;
        index++;
    }
}
System.out.println("Total correct:" + correct + ". Total incorrect: " + incorrect + ".");

Any help is appreciated, thanks.

You never reset the index value to be back to 0 before looping through the answers you recieved. So I believe your program is trying to access array spots that do not exist such as 3,4,5 becuase you created an array for only 3 Strings

1 Mod to your program to make it more user friendly and easier to debug would be to accept lowercase answers too.

Also, the program does not tell the user which question they are telling them was wrong or right, which if changed could help you understand the problem within your program.

This section:

if(userAnswer[index].equals(rightAnswer[index]))
    {
    System.out.println("Correct!");
    correct++;
    index++;
    }
if(!(userAnswer[index].equals(rightAnswer[index])))
    {
    System.out.println("Incorrect. The right answer is " + rightAnswer[index] + ".");
    incorrect++;
    index++;
    }

Needs to be in some kind of for loop. It's technically in a for-loop, but you're incrementing index yourself so it's not effectively in a for-loop.

It should work if you do something like this:

int correct = 0;
int incorrect = 0;
for(i = 0; i < 3; i++) {
  if(userAnswer[i].equals(rightAnswer[i])) {
      System.out.println("Correct!");
      correct++;
    }   

  if(!(userAnswer[i].equals(rightAnswer[i]))) {
      System.out.println("Incorrect. The right answer is " + rightAnswer[i] + ".");
      incorrect++;
    }   
}

EDIT

Also, as a general rule you shouldn't be incrementing your counter variables in a for-loop. The for-loop does it already. Notice how I didn't increment i myself in my code. Each time the for-loop is executed, i will be incremented before i < 3 is evaluated.

It appears that you are not resetting the index after collecting user answers, so at the point you reach the block that verifies the answers index is already 2, so only the last element of the array is examined by the code that verifies your answers. Basically what is happening is this:

  • Start loop (index starts 0)
  • Get your first answer (index now equals 1)
  • Get your second answer (index now equals 2)
  • Get your third answer (index still equals 2)
  • Output result for index (index is still 2, so only the last answer is processed)
  • Increment index, return to start of loop (index becomes 3, which terminates your loop)

The purpose of your loop is to iterate through the index of your array, but you are causing unintended behavior by manually incrementing the index after each time you collect an answer. The easy fix is to break the code that tests your answers into its own loop, so you can start the index over again. I will add code to the answer if this does not help you figure it out.

This may be what you are trying to do, again, I don't understand fully the question:

String questions[] = {
    "What planet has the largest rings? \n\nA. Neptune \nB. Saturn \nC. Jupiter",
    "What planet has a large redspot? \n\nA. Neptune \nB. Saturn \nC. Jupiter",
    "What planet is farthest from the sun? \n\nA. Neptune \nB. Saturn \nC. Jupiter"
};
String rightAnswer[] = { "B", "C", "A" };
String answer = null; // the user's answer
for (int i = 0; i < questions.length; i++) {
    do {
        answer = JOptionPane.showInputDialog(questions[i]);
    } while (!(answer.equals("A")|| answer.equals("B") || answer.equals("C")));
    String x = (answer.equals(rightAnswer[i])) ? "correct" : "incorrect.\nThe correct answer was " + rightAnswer[i];
    JOptionPane.showMessageDialog(null, "Your answer was " + x + ".");
}

Please excuse my style.

I believe most of the earlier posters have answered you and sketched out (among other answers) something similar. I'll just post this since I took the clicks.

public class AstroQuiz {

    final public void run () {
        String[] questions = {
            "What planet has the largest rings? \n\nA. Neptune \nB. Saturn \nC. Jupiter",
            "What planet has a large redspot? \n\nA. Neptune \nB. Saturn \nC. Jupiter",
            "What planet is farthest from the sun? \n\nA. Neptune \nB. Saturn \nC. Jupiter"
        }
        String rightAnswers[] = { "B", "C", "A" };
        String validChoices[] = {"A", "B", "C"}

        int i = 0;
        int correct = 0;
        for (String question : questions) {
            String choice = askQuestionAndGetAnswer(question, validChoices);
            if(isCorrectAnswer(rightAnswers, i, choice)) {
                correct++;
                /* display "you got it!" here .. */
            } else {
                /* display "wrong answer!" here ... */
            }
            i++
        }
        System.out.format("Total correct:%d. Total incorrect: %d.\n", correct, questions.length - correct;)
    }

    final private String askQuestionAndGetAnswer(String question, String[] validAnswers) {
        String answer = null;
        boolean haveValidResponse = false;
        while (!haveValidResponse){
            answer = JOptionPane.showInputDialog(question);
            haveValidResponse = isValidResponse(answer, validAnswers)
        }
        return answer;
    }

    final private boolean isValidResponse(String response, String[] validAnswers) {
        for (String s : validAnswers) {
            if(response.equals(s))
                return true;
        }
        return false;
    }

    final private boolean isCorrectAnswer (String[] correctionAnswers, int questionIndex, String answer) {
        return correctionAnswers[questionIndex].equals(answer);     
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM