我试图在程序中打印出一个 char 数组,但在我的控制台中,该数组显示为 5 个框。
我的代码是一个猜谜游戏,取一个字母并扫描 inputArray (char) 来查找匹配项。如果存在匹配,则会将正确猜测的字母添加到 currentGuessArray 中的相应位置。我没有正确填充数组吗?
for (int i = 0; i == lengthOfWord; i++) {
if (guess.charAt(0) == inputArray[i]) {
currentGuessArray[i] = guess.charAt(0);
}
}
System.out.println(currentGuessArray);
这就是我当前输出的内容
我的完整代码是
public class Console {
static String input = "";
public static String get() {
@SuppressWarnings("resource")
System.out.println("Enter the word to guess");
Scanner s = new Scanner(System.in);
input = s.nextLine();
return input;
}
}
public class WordGuess {
public static void guess() {
Scanner s = new Scanner(System.in);
String guess;
int trys = 0;
String input = ConsoleView.input;
int length = input.length();
char[] inputArray = input.toCharArray();
boolean[] currentGuess = new boolean[length];
char[] currentGuessArray = new char[length];
while (currentGuessArray != inputArray) {
System.out.println("Key in one character or your guess word:");
trys++;
guess = s.nextLine();
int guessLength = guess.length();
if (guessLength == 1) {
for (int i = 0; i == length; i++) {
if (guess.charAt(0) == inputArray[i]) {
//currentGuess[i] = true;
currentGuessArray[i] = guess.charAt(0);
}
}
System.out.println(Arrays.toString(currentGuessArray));
} else if (guess.equals(input)) {
System.out.println("You're correct!");
break;
}
else if (currentGuessArray == inputArray) {
System.out.println("Congratulations, you got the word in " + trys);
}
}
}
}
最佳答案
它不起作用,因为您的 for
循环永远不会循环:
for (int i = 0; i == length; i++)
for
中的第二个表达式是循环继续的条件。因此,在这种情况下,i == length
立即为 false,并且循环永远不会运行,这就是为什么您的数组 currentGuessArray
中包含错误值。
将其更改为:
for (int i = 0; i < length; i++)
你应该没问题。
顺便说一句,您的 while
循环也将永远执行。 (currentGuessArray != inputArray)
始终为 false,因为这些是引用,而 !=
比较引用。您需要比较数组的元素以查看它们是否相同。 (我很确定Arrays
中有一个方法可以做到这一点。)
关于java - 打印字符数组输出空框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36104373/