java—在数组中查找匹配值

jdgnovmf  于 2021-07-11  发布在  Java
关注(0)|答案(2)|浏览(479)

我的任务是分配nummatches,其中uservalues中的元素数等于matchvalue。uservalues包含num\u vals元素。它将通过以下输入进行测试:
匹配值:2,用户值:{2,1,2,2}
匹配值:0,用户值:{0,0,0,0}
匹配值:10,用户值:{20,50,70,100}

import java.util.Scanner;

public class FindMatchValue {
    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);

        final int NUM_VALS = 4;
        int[] userValues = new int[NUM_VALS];
        int i;
        int matchValue;
        int numMatches = -99; // Assign numMatches with 0 before your for loop

        matchValue = scnr.nextInt();
        for (i = 0; i < userValues.length; ++i) {
            userValues[i] = scnr.nextInt();
        }
        // Anything above this can't be changed.
        numMatches = 0;
        if (matchValue == numMatches) {
            numMatches = numMatches + 1;
        }
        // Anything below this can't be changed.
        System.out.println("matchValue: " + matchValue + ", numMatches: " + numMatches);
    }
}

你的产出 matchValue: 2, numMatches: 0 预期产量 matchValue: 2, numMatches: 3 你的产出 matchValue: 0, numMatches: 1 预期产量 matchValue: 0, numMatches: 4 你的产出 matchValue: 10, numMatches: 0 预期产量 matchValue: 10, numMatches: 0 唯一能让不同输入工作的方法是将nummatches从0更改为匹配matchvalue中的一个其他值,而不是同时匹配所有3个值。

wrrgggsh

wrrgggsh1#

您需要访问数组的所有元素并增加 numMatches 每一场比赛。

numMatches = 0;
for (int x = 0; x < userValues.length; x++) {
    if (matchValue == userValues[x]) {
        numMatches = numMatches + 1;   
    }
}

注意:你可以写 numMatches = numMatches + 1 也作为 numMatches += 1 .
此更改后的示例运行:

2
2 1 2 2
matchValue: 2, numMatches: 3
rjzwgtxy

rjzwgtxy2#

我认为您只想在数组中找到与指定值相等的值的数目。您可以使用如下java流轻松完成:

private static long getNumMatches(final int[] arr, final int matchValue) {
    return  Arrays.stream(arr)
            .filter(i -> i == matchValue)
            .count();
}

您可以对任意多的输入案例重复使用此功能:

int[] input1 = {2, 1, 2, 2};
int matchValue1 = 2;
int[] input2 = {0, 0, 0, 0};
int matchValue2 = 0;
int[] input3 = {20, 50, 70, 100};
int matchValue3 = 10;

System.out.println("matchValue: " + matchValue1 + ", numMatches: " + getNumMatches(input1, matchValue1));
System.out.println("matchValue: " + matchValue2 + ", numMatches: " + getNumMatches(input2, matchValue2));
System.out.println("matchValue: " + matchValue3 + ", numMatches: " + getNumMatches(input3, matchValue3));

相关问题