我遇到了麻烦,也许你可以帮助我: 我有 3 个字符串,例如:word1、word2、word3,我必须用它们构建一个矩阵,如下所示: 第一行:word1("ABC"),第二行:word2("DEF"),第三行:word3("GHI")。
A|B|C
D|E|F
G|H|I
我需要这个,因为之后我必须检查形成的单词(“ADG”,“BEH”,“CFI”)是否在单词数组中。我不知道如何将这些字符串放入矩阵中,以便我可以检查。任何帮助都是有用的。 谢谢
最佳答案
基于此评论:
the words have the same size, because the matrix is actually like a puzzle. I choose randomly 3 words from an array, put them in a matrix and check after that if the words resulted are from the same array.
为了使这项工作顺利进行,我将假设一些事情(因为我们没有足够的信息):
您有一个
String
数组,其中包含所有单词private String[] words;
您有一个方法可以从此数组中随机选取 3 个
String
。private String s1, s2, s3; public void pickThreeRandomWords() { s1 = aRandomWord(words); s2 = aRandomWord(words); s3 = aRandomWord(words); //or maybe another fancy algorithm to get this... }
因此,您需要一个基于这 3 个 String
的 char
数组。这段代码可以为您完成这项工作:
public char[][] createMatrixFromStrings(String s1, String s2, String s3) {
char[][] theMatrix = new char[3][]; //yes, hardcoded
theMatrix[0] = s1.toCharArray();
theMatrix[1] = s2.toCharArray();
theMatrix[2] = s3.toCharArray();
return theMatrix;
}
当然,如果您想让此方法支持超过 3 个 String
,您可以使该方法接收随机数量的 String
:
public char[][] createMatrixFromStrings(String ... strings) {
if (strings == null || strings.length == 0) return null;
char[][] theMatrix = new char[strings.length][];
int i = 0;
for(String s : strings) {
theMatrix[i++] = s.toCharArray();
}
return theMatrix;
}
关于java - 如何将字符串放入矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16121388/