当程序要求输入的次数与单词长度一样多时,我希望获得一些关于该部分编码的帮助。
因此,当我们启动程序时,它会从数组中随机选择一个单词,例如,如果我们要查找的单词是“team”,则意味着我们有四个猜测。
我试图用下面的代码片段来解决这个问题。看起来很简单,但我错过了一些东西:
while(!guess.equals(choosenWord) && letters <= choosenWord.length()) {
System.out.print("Your guess is: ");
guess = sc.nextLine();
我需要一些提示的下一部分是,如果我们在字符中有一些匹配项,则应显示找到的字符,并应在其他任何地方显示“-”符号:例如,该词仍然是“team”,我们'正在寻找,我们的猜测是“baby”,而不是“--a-”将被显示。
感谢您的建议。
import java.util.Scanner;
public class FindTheWord {
public static void main(String[] args) {
findTheWord();
}
public static void findTheWord() {
Scanner sc = new Scanner(System.in);
String[] words = {
"dog", "cat", "house", "love", "friend", "paper", "summer", "chips",
"number", "file", "program", "lotto", "work", "funny", "database",
"team", "profile", "facebook", "bean", "winter", "spring", "java",
"examination", "hospital", "birth", "baby", "newborn", "airplane",
"kindergarten", "autumn"};
int randomWord = (int) (Math.random() * 31);
String choosenWord = " ";
int letters = 0;
String guess = " ";
char ch = ' ';
for (int i = 0; i < words[randomWord].length(); i++) {
choosenWord = words[randomWord];
}
for (int j = 0; j < choosenWord.length(); j++) {
letters = choosenWord.length();
while(!guess.equals(choosenWord) && letters <= choosenWord.length()) {
System.out.print("Your guess is: ");
guess = sc.nextLine();
}
}
System.out.println(words[randomWord]);
System.out.println(letters);
}
}
最佳答案
这是一种使用三元运算符的解决方案 (? :
):
...
guess = sc.nextLine();
for (char c : chosenWord.toCharArray()) {
System.out.print(guess.contains(String.valueOf(c)) ? c : '-');
}
...
关于java - 在Java中如何根据单词的长度来定义猜测的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59706253/