如何总结阵列选择框<;整数>;JavaFX的值
我认为我的Java代码写得很好,但仍然得到预期的错误 代码如下: 所有程序都满足要求,让我直接进入有问题的代码部分如何总结阵列选择框<;整数>;JavaFX的值,java,javafx,Java,Javafx,我认为我的Java代码写得很好,但仍然得到预期的错误 代码如下: 所有程序都满足要求,让我直接进入有问题的代码部分 Int sumofc = 0; VBox vlay = new VBox(10); ChoiceBox<Integer> c1[] = new ChoiceBox[10] For (int x=0;x<10;x++){ c1[x] = new ChoiceBox<>(); C1[x].getItems().add(1); C
Int sumofc = 0;
VBox vlay = new VBox(10);
ChoiceBox<Integer> c1[] = new ChoiceBox[10]
For (int x=0;x<10;x++){
c1[x] = new ChoiceBox<>();
C1[x].getItems().add(1);
C1[x].getItems().add(2);
C1[x].getItems().add(3);
Vlay.getChildren().add(c1[x]);
sumofc += c1[x].getValue();
}
Int-sumofc=0;
VBox vlay=新的VBox(10);
ChoiceBox c1[]=新的ChoiceBox[10]
对于(int x=0;x您在将选择框添加到场景之前读取选择框中的值。这意味着用户没有以任何方式与ChoiceBox
es交互。相反,您应该在用户以有意义的方式与控件交互时读取,例如,通过选择不同的值
此外,默认情况下选择的值为null
,这会在尝试自动取消装箱时导致NullPointerException
,因为它相当于
sumofc += c1[x].getValue().intValue();
考虑到这些事实,您可以重写类似以下内容的代码:
VBox vlay = new VBox(10);
ChoiceBox<Integer> c1[] = new ChoiceBox[10];
InvalidationListener listener = o -> {
int sumofc = 0;
for (ChoiceBox<Integer> cb : c1) {
Integer value = cb.getValue();
if (value != null) {
sumofc += value;
}
}
// do something with sumofc
System.out.println(sumofc);
};
for (int x = 0; x < c1.length; x++) {
c1[x] = new ChoiceBox<>();
c1[x].getItems().addAll(1, 2, 3);
vlay.getChildren().add(c1[x]);
c1[x].valueProperty().addListener(listener);
}
VBox vlay=新的VBox(10);
ChoiceBox c1[]=新的ChoiceBox[10];
无效侦听器侦听器=o->{
int-sumofc=0;
用于(选择框cb:c1){
整数值=cb.getValue();
if(值!=null){
sumofc+=值;
}
}
//用sumofc做点什么
系统输出打印LN(sumofc);
};
对于(int x=0;x
我猜那些大小写错误只是打字错误???了解您对sumofc
的期望将帮助我们帮助您。如果我像这样使用(我的“求和选择值btn”):btn.setOnAction(e->system.out.println(c[0].getValues()+c[1].getValues())在for循环之外,它进行求和,但我希望它将数组choiceBox值求和为数组中的整数