JAVA:在数组中查找值

时间:2022-10-30 13:09:54

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.

将numMatches设置为userValues(具有NUM_VALS个元素)中等于matchValue的元素数。例如:如果matchValue = 2且userValues = {2,2,1,2},则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,

测试matchValue = 0,

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

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

Expected value: 5

预期价值:5

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

你的价值:4 << <这是我出错的地方。< p>

2 个解决方案

#1


2  

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.

这个块是不正确的,你将numMatches分配给数组的索引值,而应该是如果numMatches的匹配增量值为1。

#2


1  

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

numMatches ++这是你需要在for循环中而不是numMatches = i;

#1


2  

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.

这个块是不正确的,你将numMatches分配给数组的索引值,而应该是如果numMatches的匹配增量值为1。

#2


1  

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

numMatches ++这是你需要在for循环中而不是numMatches = i;