gpt4 book ai didi

java - 如何检查和匹配 arraylist 元素的可能组合

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:41:39 26 4
gpt4 key购买 nike

String [] A = {"High","Medium","Low"};
String [] B = {"High","Medium","Low"};
String [] C = {"High","Medium","Low"};
String [] D = {"High","Medium","Low"};
String [] E = {"High","Medium","Low"};
String [] F = {"High","Medium","Low"};

JComboBox Ai = new JComboBox(A); JComboBox Bi = new JComboBox(B);
JComboBox Ci = new JComboBox(C); JComboBox Di = new JComboBox(C);
JComboBox Ei = new JComboBox(E); JComboBox Fi = new JComboBox(F);

....

//add the user choice in arrayList
ArrayList<String> a = new ArrayList<String>();
a.add((String) Ai.getSelectedItem());
a.add((String) Bi.getSelectedItem());
a.add((String) Ci.getSelectedItem());
a.add((String) Di.getSelectedItem());
a.add((String) Ei.getSelectedItem());
a.add((String) Fi.getSelectedItem());

已编辑:
设想:有 6 组(Ai、Bi、Ci、Di、Ei、Fi)可供选择。在每组上,有3个子选项(高(H),中(M),低(L))。用户需要在6个组中的每一个上选择一个

选择可以是例如"HHHLLL"或 "MMMLLM"或 "HHLLMM"等

在不编写很多 else if 的情况下检查和匹配用户选择的最佳方法是什么?例如

if(Ai=="High" && Bi=="High" && Ci=="Low" && Di=="High" && Ei=="Low" && Fi=="Medium") {
System.out.println("Good Choice");
}

谢谢。

最佳答案

首先,您不需要为每个 JComboBox 提供新的选择列表。

String[] choices = {"High", "Medium", "Low"};

JComboBox ai = new JComboBox(choices);
JComboBox bi = new JComboBox(choices);
JComboBox ci = new JComboBox(choices);
JComboBox di = new JComboBox(choices);
JComboBox ei = new JComboBox(choices);
JComboBox fi = new JComboBox(choices);

(Java中的变量通常以小写字母开头,所以我将变量名改为小写。)


接下来,您可以将所有六个 JComboBox 放在一个数组中。您马上就会明白为什么这很有用。

JComboBox[] boxes = {ai, bi, ci, di, ei, fi};

现在,您可以像这样制作您的用户选择字符串:

// Create an ArrayList of Strings, where each string is either "H", "M", or "L"
ArrayList<String> userChoice = new ArrayList<String>()

for (JComboBox box : boxes) {
// Go through this code once for each JComboBox in boxes
// The first time through, "box" means the first JComboBox
// The second time through, "box" is the second JComboBox, etc.
if (box.getValue().equals("High")) {
userChoice.add("H");
} else if (box.getValue().equals("Medium")) {
userChoice.add("M");
} else if (box.getValue().equals("Low")) {
userChoice.add("L")
}
}

您可能不熟悉 for-each 循环。它的意思是“对某物数组中的每个某物执行一次此代码。”


如果您使用此代码,您最终会得到一个名为 userChoice 的 ArrayList,它具有类似于 ["H", "H", "M", "M", "L", "L"] 的内容。

关于java - 如何检查和匹配 arraylist 元素的可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2549535/

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