所以我需要将一个字符串数组添加到一个名为square的二维数组中。数组正方形是一个10乘10的数组,其中第一行initStrings将与正方形匹配。
IE - static String[] strings = {"hello"}
h
位于正方形数组的第一个位置,e
位于第二个位置,依此类推。我想知道如何做到这一点。
static String[] initStrings =
{
"...../...\\",
"..\\.......",
"......./..",
"..........",
"........\\.",
"..........",
"..........",
".....\\../.",
"..\\....../",
".........."
};
我知道我需要一个嵌套的for循环。
的内容for (col = 0; col < 10; col++)
{
for (rows = 0; rows < 10; rows ++)
{
// what goes here?
}
}
答案 0 :(得分:1)
char[][] squares=new char[10][10];
String[] initStrings = { "...../....", "../.......", "......./..", "..........", "......../.", "..........", "..........", "...../../.", "../....../", ".........." };
int i=0;
for(char[] squareRow:squares)
squareRow=initStrings[i++].toCharArray();
答案 1 :(得分:0)
这可能会有所帮助:
static String[] initStrings = { "...../...\", "..\.......", "......./..", "..........", "........\.", "..........", "..........", ".....\../.", "..\....../", ".........." };
char[][] squares = new char[10][10];
int row, col;
for (row = 0; row < 10; rows ++)
{
for (col = 0; col < 10; col++)
{
squares[row][col] = initStrings[row].charAt(col);
}
}
// print squares
for (row = 0; row < 10; rows ++)
{
for (col = 0; col < 10; col++)
{
System.out.print(squares[row][col] + " ");
}
System.out.print("\n");
}
答案 2 :(得分:0)
这是另一种可能的解决方案。这有点矫枉过正,但我喜欢地图和列表:)这样做的一个优点是,如果你在你的initStrings中添加一个超过10个字符的新字符串,它仍然应该完成。但是,也许那会很糟糕......
String[] initStrings = {"...../...\\", "..\\.......", "......./..", "..........", "........\\.", "..........", "..........", ".....\\../.", "..\\....../", ".........." };
Map<Integer, List<String>> columnEntries = new TreeMap<Integer, List<String>>();
for(String str : initStrings) {
for(int i = 0; i < str.length(); i++) {
if(!columnEntries.containsKey(i)) {
columnEntries.put(i, new ArrayList<String>());
}
columnEntries.get(i).add(str.substring(i,i+1));
}
}
//Print results...
for(Entry<Integer, List<String>> e : columnEntries.entrySet()) {
System.out.println(e.getKey());
System.out.println(e.getValue());
}