为什么我的程序错误地增加了这个变量?

问题描述 投票:0回答:1

我的程序使用一个由四个数字组成的字符串变量和一个由另外四个数字组成的字符数组。它应该为字符串和数组之间的值匹配的字符数以及值索引匹配的字符数增加单独的变量。当我试图解释重复的数字时,这对我来说变得很困难。值和索引中匹配的字符数的变量递增不正确,我不明白为什么。

如果这个问题太模糊或不理想,我深表歉意;这是我的第一篇文章。

例如: 给定一个字符串(“guess”)“1222”和一个字符数组(solChars){“1”,“2”,“1”,“2”},匹配数字的数量(numCorrNums)应该是 3 并且匹配位置的数量 (numCorrPositions) 也应该为 3。相反,我的程序将 numCorrNums 输出为 3(正确),将 numCorrPositions 输出为 2(错误)。

这是代码:

numCorrNums = 0;
numCorrPositions = 0;
                    
// arrays to account for duplicates
boolean[] matchedPositionIndices = new boolean[4];
            
for (int i = 0; i < guess.length(); i++) {
      char curChar = guess.charAt(i);
                
      if (curChar == solChars[i] && !matchedPositionIndices[i]) { 
            numCorrPositions++;
            numCorrNums++;
            matchedPositionIndices[i] = true;
      } else { // loop for matching number
            for (int j = 0; j < solChars.length; j++) {
                  if (curChar == solChars[j] && !matchedPositionIndices[j]) {
                  numCorrNums++;
                  matchedPositionIndices[j] = true;
                  break; // prevent incorrect indice matching 
                  }
            }
      }
}
java for-loop char
1个回答
0
投票

代码中有一处位置递增

numCorrNums
,但不递增
numCorrPositions
。显然,如果位置正确,则数字也正确。不确定为什么你有两个变量。

if (curChar == solChars[j] && !matchedPositionIndices[j]) {
    numCorrNums++;
    numCorrPositions++;
    matchedPositionIndices[j] = true;
    break; // prevent incorrect indice matching
}

这一变化使两者都重要

3

© www.soinside.com 2019 - 2024. All rights reserved.