进行等式测试以使用 char 和数组

Getting an equality test to work with char's and an array

我的任务是创建一个接受单个字符并进行相等性检查以查看它是否与数组中的任何字符匹配的方法。

对于找到匹配项的次数,计数器应该会增加。我很确定 for 循环的语法是正确的,但我不知道如何 运行 进行相等性检查。

if(tiles.toCharArray()==letter) 是我目前的尝试。关于如何切换或更改这行代码以使相等性测试起作用的任何想法?

public class ScrabblePlayer {

  private String tiles;
  int count;

  // A String representing all of the tiles that this player has
  public char ScrabblePlayer() {
    tiles = "";
  }

  public int getCountOfLetter(char letter) {
    count = 0;
    for(char character : tiles.toCharArray()) {
    if(tiles.toCharArray() == letter);
    count += 1;
  }
  return count;
}

应该是这样的:-

if(character == letter) {
    count += 1;
}

附带说明一下,我认为 public char ScrabblePlayer() 应该是 public ScrabblePlayer() 如果它应该是构造函数。

在您的 getCountOfLetter 方法代码中,您有两个问题:

  1. if 条件行末尾无用的分号 ;
  2. 并且您在 if 条件中使用了错误的变量,tiles.toCharArray() 应该替换为 character,因为您正在循环它。

你的代码应该是这样的:

public int getCountOfLetter(char letter) {
    count = 0;
    for(char character : tiles.toCharArray()) {
        if(character == letter)
           count ++;
    }
    return count;
}