JAVA:在数组中查找值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39761124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:36:40  来源:igfitidea点击:

JAVA: Finding Values in an Array

javaarraysarraylist

提问by Java123

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}

用户值 = {0, 0, 0, 0, 0}

Expected value: 5

预期值:5

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

您的价值:4 <<< 这是我出错的地方。

回答by Himanshu Bhardwaj

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。

回答by Ajay Pal

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

numMatches++这是您需要在 for 循环中执行的操作,而不是 numMatches = i;