Home > other >  How do I sum string arrays in java
How do I sum string arrays in java

Time:07-21

I am creating a simulated test that is ready to be graded. My main module request user input of 20 multiple choice answers (A,B,C,D). I am using a for loop to populate both arrays. I next have an If .equals statements that compares the two arrays for correct answer and in correct answer. `

My current out put is:

The correct answer to question 16 is: C Your answer to question 16 is: C Question 16 is correct

The correct answer to question 17 is: C Your answer to question 17 is: A Question 17 is incorrect

Next

I am attempting to simulate an out put of:

You passed the exam with a grade of 90%. Congratulations!

Number of correct answers: 18 Number of incorrect answers: 2

Here is the portion of code I am working on

int arraySize;

    arraySize = 20;
    
    // Declare and assign the variables to create the parallel array
    int count;
    
  
    // Access the contents of both arrays
    for (count = 0; count <= arraySize - 1; count  ) {
        System.out.println();
        // Message to diplay the Answerkey and testAnswer
        System.out.println("The correct answer to question "   (count   1)   " is: "   answerKeyArray[count]);
        System.out.println("Your answer to question "   (count   1)   " is: "   testAnswers[count]);
        
        // Find the correct and incorrect answers
        if (answerKeyArray[count].equals(testAnswers[count])) {
            
            // Message to display the answer is correct
            
            System.out.println("Question "   (count   1)   " is correct ");
            
        } else {
            
            // Message to display the answer is incorrect
            System.out.println("Question "   (count   1)   " is incorrect ");

CodePudding user response:

you can make a counter variable inside the for loop, which would make it a local variable, and it would be voided after it goes outside the for loop. Below is an example

for(int i = 0; i < arraySize; i  ){
int correctCounter = 0;
int incorrectCounter = 0;
if(PretendThisIsAConditional){
counter  ;
}
else{
incorrectCounter  ;
System.out.println("Number of correct answers: "   correctCounter   "Number of incorrect answers: "   incorrectCounter);
}

If you have the number correct inside a string for whatever reason you can do

int numCorrect = Integer.parseInt(String);
  • Related