gpt4 book ai didi

Java将单个字符从char数组转换为String数组

转载 作者:行者123 更新时间:2023-12-02 02:17:59 24 4
gpt4 key购买 nike

我正在从文本文件中读取一个单词(程序),我想将其存储到名为 word1 的二维数组中。为此,我读入文件并将其存储到占位符数组中。然后,我将此占位符数组转换为字符数组,以便将每个字母分开。我现在想要将此字符数组中的单个字母发送回我之前创建的字符串数组 (word1)。最终,我希望 word1 数组变成这样

String word1[][] = {
{"p", "*"}, {"r", "*"}, {"o", "*"}, {"g", "*"}, {"r", "*"}, {"a", "*"}, {"m", "*"},
};

一切正常,直到最后一位我尝试将 char 数组中的各个字母转换回 word1 数组。

FileReader file = new FileReader("C:/Users/Mark/Desktop/Java/Workshop 2/hangman.txt");
BufferedReader reader = new BufferedReader(file);

String text = "";
String line = reader.readLine(); //Keeps reading line after line
while (line != null){
text += line;
line = reader.readLine();
}

String word1[][] = {
{"", "*"}, {"", "*"}, {"", "*"}, {"", "*"}, {"", "*"}, {"", "*"}, {"", "*"},
};

String placeholder[] = text.split("\\s+"); //Converts text into an array

String s = "";
for (String n:placeholder){
s+= n;
}

char[] charArray = s.toCharArray();

for (int i = 0; i < 6; i++){
word1[i][0] = new String(charArray[i]); //This is where problem occurs
}

最佳答案

String 中没有定义 String(char) 构造函数。所以你不能这样做:

String word1[][]  = ...;
word1[i][0] = new String(charArray[i]); //This is where problem occurs

您需要的是String.valueOf(char c):

word1[i][0] = String.valueOf(charArray[i]); 

关于Java将单个字符从char数组转换为String数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48995559/

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