gpt4 book ai didi

java - 在Java中,我的数组似乎只存储我最后添加的值

转载 作者:行者123 更新时间:2023-12-02 12:56:30 25 4
gpt4 key购买 nike

嗨,正如你所看到的,我对此相当陌生,但我正在尝试制作一个非常基本的绞刑吏游戏。如果用户猜测是正确的,我想制作一个到目前为止他猜对的字母的数组。但我得到的只是数组中保存的最后一个键盘输入。

这是代码。

do {
System.out.println("Choose a letter: ");
firstGuess = keyboard.next();
String [] GuessedWordSoFar = new String[wordToGuess.length()];
char[] wordToGuessInCharArray = wordToGuess.toCharArray();

if((new String(wordToGuessInCharArray).contains(firstGuess))){
int index = -1;
char c = firstGuess.charAt(0);
for(int z = 0; (z <wordToGuessInCharArray.length)&&
(index == -1); z++){

if( wordToGuessInCharArray[z] == c) {
index = z;
System.out.println("Correct");
GuessedWordSoFar[index] = firstGuess;
}
}
System.out.println(Arrays.asList(GuessedWordSoFar));
}

最佳答案

问题在于 GuessedWordSoFar 数组的初始化位于 do-while 循环内,因此每次循环执行时都会重置。尝试下面的代码,这应该可以修复您的错误。

String [] GuessedWordSoFar = new String[wordToGuess.length()];
do {
System.out.println("Choose a letter: ");
firstGuess = keyboard.next();

char[] wordToGuessInCharArray = wordToGuess.toCharArray();

if((new String(wordToGuessInCharArray).contains(firstGuess))){
int index = -1;
char c = firstGuess.charAt(0);
for(int z = 0; (z <wordToGuessInCharArray.length)&&
(index == -1); z++){

if( wordToGuessInCharArray[z] == c) {
index = z;
System.out.println("Correct");
GuessedWordSoFar[index] = firstGuess;
}
}
System.out.println(Arrays.asList(GuessedWordSoFar));
}

关于java - 在Java中,我的数组似乎只存储我最后添加的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44406723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com