有人可以帮我一把吗?我有多维数组存储String的值。
private static JMenu[] Menu_Bars;
private static final String[] Menu_names = {"File", "Edit", "View", "Search", "Info"};
private static final String[][] Menu_Item_Data =
{{"New File","Open File", "Close", "Close ALl", "Save", "SaveAs...", "Print"},
{"Undo Typing", "Redo", "Cut", "Copy", "Paste", "Delete", "Select All"},
{"Text Color", "Font", "Text Size", "Background Color"},
{"Search..."},
{"Spaces count", "Words Count", "Sentences Count"}};
所以...我的多维数组包含数组,所以我怎么能得到数组包含的字符串。
我遇到了一种方法。
//menuComponent
private static void menuComponent(final JFrame frame) {
bar = new JMenuBar();
Menu_Bars = new JMenu[5];
int count = 0;
for(int i=0;i<5;i++) {
Menu_Bars[i] = new JMenu(Menu_names[i]);
}
JMenuItem[] item = new JMenuItem[count = Menu_Item_Data[0][1].length()];
for(int i=0;i<count;i++) {item[i] = new JMenuItem(Menu_Item_Data[0][0] /*How to pull Strings from Array in Argumments?*/ ); Menu_Bars[0].add(item[i]); }
JMenuItem[] item1 = new JMenuItem[count = Menu_Item_Data[0][2].length()];
for(int i=0;i<count;i++) {item1[i] = new JMenuItem(Menu_Item_Data[0][1]); Menu_Bars[1].add(item1[i]); }
JMenuItem[] item2 = new JMenuItem[count = Menu_Item_Data[0][3].length()];
for(int i=0;i<count;i++) {item2[i] = new JMenuItem(Menu_Item_Data[0][2]); Menu_Bars[2].add(item2[i]); }
JMenuItem[] item3 = new JMenuItem[count = Menu_Item_Data[0][4].length()];
for(int i=0;i<count;i++) {item3[i] = new JMenuItem(Menu_Item_Data[0][3]); Menu_Bars[3].add(item3[i]); }
JMenuItem[] item4 = new JMenuItem[count = Menu_Item_Data[0][5].length()];
for(int i=0;i<count;i++) {item4[i] = new JMenuItem(Menu_Item_Data[0][4]); Menu_Bars[4].add(item4[i]); }
for(int i=0;i<5;i++)
bar.add(Menu_Bars[i]);
frame.setJMenuBar(bar);
}
答案 0 :(得分:1)
使用嵌套for循环。
final String[][] Menu_Item_Data = {
{ "New File", "Open File", "Close", "Close ALl", "Save", "SaveAs...", "Print" },
{ "Undo Typing", "Redo", "Cut", "Copy", "Paste", "Delete", "Select All" },
{ "Text Color", "Font", "Text Size", "Background Color" }, { "Search..." },
{ "Spaces count", "Words Count", "Sentences Count" } };
for(int i = 0; i < Menu_Item_Data.length; ++i)
{
for(int j = 0; j < Menu_Item_Data[i].length; ++j)
{
System.out.println("["+ i +"][" + j +"] " + Menu_Item_Data[i][j]);
}
}
Output:
[0][0] New File
[0][1] Open File
[0][2] Close
[0][3] Close ALl
[0][4] Save
[0][5] SaveAs...
[0][6] Print
[1][0] Undo Typing
[1][1] Redo
[1][2] Cut
[1][3] Copy
[1][4] Paste
[1][5] Delete
[1][6] Select All
[2][0] Text Color
[2][1] Font
[2][2] Text Size
[2][3] Background Color
[3][0] Search...
[4][0] Spaces count
[4][1] Words Count
[4][2] Sentences Count
答案 1 :(得分:0)
循环:
List<String> allStrings = new ArrayList<String>();
for (String[] arr1 : arr2) {
for (String s : arr1) {
allStrings.add(s);
}
}
Java 8解决方案:
List<String> list = Arrays.stream(Menu_Item_Data)
.flatMap(arr1 -> Arrays.stream(arr1))
.collect(Collectors.toList());