gpt4 book ai didi

java - 如何获取一个字符来替换字符串中的部分(java)

转载 作者:行者123 更新时间:2023-12-01 12:20:48 26 4
gpt4 key购买 nike

我目前正在 CS 入门课上做一个数组项目,我必须成功制作一款刽子手游戏。我认为我的开始相当正确,但我似乎无法掌握如何将字符替换为字符串。我必须有一个方法来创建一个随机单词,所以这就是为什么我的代码中有一个方法。看看我到目前为止有什么:

import java.util.Random;
import java.util.Scanner;
public class ProjectNum2 {
//creator's name

public static void main(String[] args) {

System.out.println("Welcome to the Hangman Word game!");

String[] wordKey = {
"loop",
"for",
"while",
"java",
"switch",
"scanner",
"else",
"double",
"integer",
"public",
"static",
"method",
"return",
"null",
"void",
"true",
"false",
"import",
"string",
"character"
};
String[] wordSpace = {
"_ _ _ _",
"_ _ _",
"_ _ _ _ _",
"_ _ _ _",
"_ _ _ _ _ _",
"_ _ _ _ _ _ _",
"_ _ _ _",
"_ _ _ _ _ _",
"_ _ _ _ _ _ _",
"_ _ _ _ _ _",
"_ _ _ _ _ _",
"_ _ _ _ _ _",
"r _ _ _ _ _",
"_ _ _ _",
"_ _ _ _",
"_ _ _ _",
"_ _ _ _ _",
"_ _ _ _ _ _",
"_ _ _ _ _ _",
"_ _ _ _ _ _ _ _ _"
};
char[] letters = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};

final int guesses = 6;

int index = 0;
index=(int) randomGen(wordKey, wordSpace);

Scanner keyboard = new Scanner(System.in);
System.out.println();
System.out.print("Choose a letter or enter zero to guess the word: ");
char letter = keyboard.nextLine().charAt(0);
}

private static Object randomGen(String[] wordKey, String[] wordSpace) {
String gameWord;
Random randIndex = new Random();
int index = randIndex.nextInt(wordKey.length);
gameWord = wordSpace[index];
System.out.print(gameWord);
return (index);

}

}

最佳答案

Java 中的字符串是不可变的,这意味着您无法更改它。您必须构建一个新的 String 对象,在您的情况下使用 String.replace(...) 方法。

关于java - 如何获取一个字符来替换字符串中的部分(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26662624/

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