0

Set numMatches to the number of elements in userValues (having NUM_VALS elements) that equal matchValue. Ex: If matchValue = 2 and userValues = {2, 2, 1, 2}, then numMatches = 3.

import java.util.Scanner;

public class FindMatchValue {
public static void main (String [] args) {
   final int NUM_VALS = 4;
   int[] userValues = new int[NUM_VALS];
   int i = 0;
   int matchValue = 0;
   int numMatches = -99; // Assign numMatches with 0 before your for loop

  userValues[0] = 2;
  userValues[1] = 2;
  userValues[2] = 1;
  userValues[3] = 2;

  matchValue = 2;

  **/* Your solution goes here  */**

  numMatches = 0;

 for(i = 0; i < NUM_VALS; ++i) {
    if(userValues[i] == matchValue)
       numMatches = i;
 }        
  System.out.println("matchValue: " + matchValue + ", numMatches: " +     numMatches);

  return;
  }
}

My solution has mistakes that I can't figure out.

Testing matchValue = 0,

userValues = {0, 0, 0, 0, 0}

Expected value: 5

Your value: 4 <<< This is where I'm going wrong.

1
  • and your question are... ? Commented Sep 29, 2016 at 3:58

3 Answers 3

3
for(i = 0; i < NUM_VALS; ++i) {
   if(userValues[i] == matchValue) {
      //numMatches = i;   //WRONG
      numMatches++;     //Correct
   }
}

This block is incorrect, you are assigning numMatches to the index value of the array rather, it should have been that if there's a match increment values of numMatches by 1.

Sign up to request clarification or add additional context in comments.

Comments

1

numMatches++ this is what you need to do in the for loop instead of numMatches = i;

Comments

1
   numMatches = 0; //initialize numMatches to 0
   for (i = 0; i < userValues.length; ++i) {
     if(userValues[i] == matchValue){
        matchValue = userValues[i]; //reassign numValue to the current array value
         numMatches +=1;//increment numValue by 1
        }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.