gpt4 book ai didi

java - 替换数组中的值

转载 作者:行者123 更新时间:2023-12-01 09:37:06 25 4
gpt4 key购买 nike

我目前正在做一个小 self 项目来创建一个刽子手游戏。我想要它,以便计算机将您必须找到的丢失字母打印为下划线,以及您已经在隐藏单词通常会出现的位置找到的字母我被困在我希望计算机每次用户输入正确的 char 时用字母替换下划线的部分。

import java.util.Arrays;
import java.util.Scanner;

public class HangmanGame {

static String hiddenWord = "marcus";
static int triesLeft = 6;
static boolean done = false;
static int length = hiddenWord.length();
static Scanner input = new Scanner(System.in);
final static int maxLength = 20;
static char[] letters = new char[20];
static char[] repeatChecker = new char[20]; //this is to help prevent the user from putting the same char multiple times
static char[] test = new char[20];
static char[] fillWord = new char[length];
static int var;
static int var2;
static char underscore = '_';




public static boolean contains(char[] arr, char i) {
for (char n : arr) {
if (i == n) {
return true;
}
}
return false;
}
public static void stringToArray(String s){
char[] stringArray = s.toCharArray();
for (char output : stringArray){
var2++;
test[var2] = output;
//System.out.println(test);

}

}
public static void createSpaces(int n){
for (int i = 0; i <= n-1; i++){
fillWord[i] = underscore;
}
System.out.println(fillWord);
}


public static void arrayLetters(){
System.out.println("Please enter a letter to guess: ");
char charInput = input.next().charAt(0);
for (int i = 0; i < length; i++){
char wordLetter = hiddenWord.charAt(i);
letters[i] = wordLetter;
if (contains(letters, charInput)){
if (contains(repeatChecker, charInput)){
System.out.println("You already did that word, try again!");
arrayLetters();
}
repeatChecker[var] = charInput;
var++;
fillWord[i] = fillWord[i].replace(charInput);
System.out.println("Nice! There is a " + charInput + " in this word!");
System.out.println(repeatChecker);
System.out.println("You have " + triesLeft + " tries left!\n");
arrayLetters();

}
if (i == length-1){
System.out.println("There is no " + charInput + " in this word!");
triesLeft--;
System.out.println("You have " + triesLeft + " tries left!\n");
if (triesLeft <= 0){
System.out.println("You failed!");
System.exit(0);

}
arrayLetters();
}
}


}

public static void main(String[] args) {
System.out.println("Welcome to my hangman game!");
stringToArray(hiddenWord);
//System.out.println(length);
createSpaces(length);
arrayLetters();
}




}

如何使用 replace()或另一个函数,正确地做到这一点,这样我的代码就可以在每次用户输入正确的 char 时用一个字符替换下划线。那hiddenWord包含。

最佳答案

你必须写

fillWord[i] = charInput;

两行之后

System.out.println(fillWord);

您打印了 repeatChecker,而不是 fillWord

关于java - 替换数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38799129/

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