JAVA:在数组中查找值

时间:2016-09-29 03:54:57

标签: java arrays arraylist

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

我的解决方案存在一些我无法弄清楚的错误。

测试matchValue = 0,

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

预期价值:5

您的价值:4&lt;&lt;&lt;这是我出错的地方。

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

std::vector