有没有一种方法可以根据Java中一个字符串中有多少个字母来创建相同字符的字符数组?
我正在尝试用Java创建一个刽子手游戏,我想知道是否有一种方法可以根据字符串中有多少字母来创建相同字符的有没有一种方法可以根据Java中一个字符串中有多少个字母来创建相同字符的字符数组?,java,arrays,string,char,Java,Arrays,String,Char,我正在尝试用Java创建一个刽子手游戏,我想知道是否有一种方法可以根据字符串中有多少字母来创建相同字符的字符数组。 例如,如果用户输入一个5个字母的单词,则创建一个带有5个下划线的char数组 这是我迄今为止一直尝试但没有成功的方法: System.out.println("Enter a word to guess"); String wordToGuess = input.nextLine(); String array[] = {"_", "_", "_",};
字符数组。
例如,如果用户输入一个5个字母的单词
,则创建一个带有5个下划线的char数组
这是我迄今为止一直尝试但没有成功的方法:
System.out.println("Enter a word to guess");
String wordToGuess = input.nextLine();
String array[] = {"_", "_", "_",};
char underscore[] = array.toCharArray();
我收到的错误消息是:
Cannot invoke toCharArray() on the array type String[]
toCharArray()方法仅在字符串上可用,而在字符串[]上不可用。这就是错误发生的原因
您可以连接数组的所有部分,然后转换为字符。例如,String.join(“,array).tocharray()
最简单的方法如下
char[] chars = new char[userinput.length()] ;
Arrays.fill(chars, '_') ;
您可以获取字符串的长度,并通过将文本转换为字符数组进行管理,如下例所示:
public static void main(String[] args) {
String testString = "This Is Test";
int stringLength = testString.length(); //Maybe you can use this.
char[] arrayName = testString.toCharArray(); //And here you can manage your array
for (int i = 0; i<=testString.length()) {
System.out.println(char[i]);
}
}
publicstaticvoidmain(字符串[]args){
String testString=“这是测试”;
int stringLength=testString.length();//也许您可以使用这个。
char[]arrayName=testString.toCharArray();//在这里您可以管理您的数组
对于(int i=0;i请尝试以下方法:
//creates a char array the same size as the word the user has given
char[] underscore = new char[wordToGuess.length()];
//fills all the items in the underscore array with '_' character
Arrays.fill(underscore, '_');
包括一个解释会提高你答案的质量。
//creates a char array the same size as the word the user has given
char[] underscore = new char[wordToGuess.length()];
//fills all the items in the underscore array with '_' character
Arrays.fill(underscore, '_');