将字符添加到Java中的字符数组中

huangapple go评论69阅读模式
英文:

Adding Char to Char Array in Java

问题

我在Java方面还是比较新,所以请容忍。我正在制作一个简单的猜词游戏,接受用户的输入。我试图将猜测的字母添加到knownLetters数组中,但出现了类型不匹配的错误。我尝试过使用.concat(),但得到了相同的类型错误。以下是我目前的代码。有任何想法或者适合新手阅读的文档资源都会很有帮助。谢谢!

编辑:感谢大家的评论!这些都非常有帮助。

public static boolean updateWithGuess(char[] knownLetters,
                                      char guessedLetter,
                                      String word) {

    System.out.println(Arrays.toString(knownLetters));

    int i = 0;
    while(word.indexOf(i, guessedLetter) != -1) {
      i = word.indexOf(i, guessedLetter) + 1;
      knownLetters += guessedLetter;
英文:

I'm still pretty new to Java so bear with me. I'm making a simple hangman game that takes input from the user. I am trying to append the guessed letter to the knownLetters array but I get a type mismatch. I tried .concat() and got the same type error. Here is where I am now. Any ideas or documentation resources (that a novice can read) would be helpful. Thanks!

Edit: Thanks for the comments, everyone! These are very helpful.

 public static boolean updateWithGuess(char[] knownLetters,
                                      char guessedLetter,
                                      String word) {

    System.out.println(Arrays.toString(knownLetters));

    int i = 0;
    while(word.indexOf(i, guessedLetter) != -1) {
      i = word.indexOf(i, guessedLetter) + 1;
      knownLetters += guessedLetter;

答案1

得分: 1

在这种情况下,使用数组并不是最佳选择,因为数组具有固定的大小,无法动态添加和删除项目,或许更好的选择是使用列表。

如果您需要简单的介绍,可以查看这里:
https://www.geeksforgeeks.org/list-interface-java-examples/

英文:

Using arrays in that case is not the best choice because arrays have a fixed size and you cannot dynamically add and remove items, maybe rather choose lists.

If you need a simple introduction, here you are:
https://www.geeksforgeeks.org/list-interface-java-examples/

答案2

得分: 0

其他人提到了 StringBuilderList,这是朝着正确方向迈出的一步,因为它们是动态的(元素数量可变)。然而,由于这个问题仅关注于跟踪记录每个被猜测的字母,所以使用集合是最合适的。一个常见的示例是 HashSet。集合不允许重复项。但是集合将允许字符的大写和小写版本都存在于集合中(因为它们具有不同的值)。因此,您可以将所有猜测和已知字母规范化为大写或小写。

英文:

Others have mentioned StringBuilder and List which are a step in the right direction as they dynamic (in number of elements). However since this question is only concerned with keeping track of each letter that was guessed a set makes the most sense. One common example is HashSet. Sets do not allow duplicates. However sets will allow both the upper and lower case versions of a character to be present in the set (since they have different values). So you could normalize all the guesses and known letters to either uppercase or lowercase.

huangapple
  • 本文由 发表于 2020年10月26日 06:40:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64529553.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定