我是编程新手,但如果用户选择了元素,我需要按元素分组;因此,我不确定我的小组将包含多少元素。 因此,我这样做是为了计算所选元素的数量,然后创建另一个语句,该语句创建表示所需元素数量的正确Group by语句。
它有效,但它看起来很笨重,我想看看是否有更好的方法可以做到这一点?
int totalOutPuts = 0;
totalOutPuts = endbox == true ? totalOutPuts + 1 : totalOutPuts;
totalOutPuts = coursebox == true ? totalOutPuts + 1 : totalOutPuts;
totalOutPuts = departmentbox == true ? totalOutPuts + 1 : totalOutPuts;
totalOutPuts = callbox == true ? totalOutPuts + 1 : totalOutPuts;
totalOutPuts = daybox == true ? totalOutPuts + 1 : totalOutPuts;
totalOutPuts = startbox == true ? totalOutPuts + 1 : totalOutPuts;
totalOutPuts = instructorbox == true ? totalOutPuts + 1 : totalOutPuts;
totalOutPuts = roombox == true ? totalOutPuts + 1 : totalOutPuts;
totalOutPuts = buildingbox == true ? totalOutPuts + 1 : totalOutPuts;
totalOutPuts = numberenrolled == true ? totalOutPuts + 1 : totalOutPuts;
int missingElements = 10 - totalOutPuts;
String groupBy = " Group by 1, 2, 3, 4, 5, 6, 7, 8, 9, 10";
if (missingElements == 9) {
groupBy = " Group by 1";
} else if (missingElements == 8) {
groupBy = " Group by 1, 2";
} else if (missingElements == 7) {
groupBy = " Group by 1, 2, 3";
} else if (missingElements == 6) {
groupBy = " Group by 1, 2, 3, 4";
} else if (missingElements == 5) {
groupBy = " Group by 1, 2, 3, 4, 5";
} else if (missingElements == 4) {
groupBy = " Group by 1, 2, 3, 4, 5, 6";
} else if (missingElements == 3) {
groupBy = " Group by 1, 2, 3, 4, 5, 6, 7";
} else if (missingElements == 2) {
groupBy = " Group by 1, 2, 3, 4, 5, 6, 7, 8";
} else if (missingElements == 1) {
groupBy = " Group by 1, 2, 3, 4, 5, 6, 7, 8, 9";
}
答案 0 :(得分:4)
循环!这是一个实施建议:
// adding all the vars to an array might improve readability
boolean checks[] = new boolean[] { endbox, coursebox, departmentbox, callbox,
daybox, startbox, instructorbox, roombox,
buildingbox, numberenrolled };
for (boolean check : checks) {
if (check) {
totalOutPuts++;
}
}
String groupBy = " Group by ";
// this isn't the best way of appending strings in Java,
// you'd be better using StringBuilder. this is for the sake of simplicity
for (int i = 1; i < totalOutPuts; i++) {
groupBy += i + ", ";
}
// append the last number
groupBy += totalOutPuts + "";
答案 1 :(得分:3)
首先要突出的是:
totalOutPuts = endbox == true ? totalOutPuts + 1 : totalOutPuts;
将布尔值与true
进行比较是没有意义的,因为它已经是一个布尔值,只需这样做:
totalOutPuts = endbox ? totalOutPuts + 1 : totalOutPuts;
除此之外,您可以进一步简化为:
totalOutPuts += endbox ? 1 : 0; // same as totalOutPuts = totalOutPuts + (endbox ? 1 : 0);
或者,更具可读性:
if(endbox) {
totalOutPuts += 1; // or ++totalOutPuts if you're into that sort of thing
}
然后在底部,你这样做:
int missingElements = 10 - totalOutPuts;
那么为什么不首先这样做呢?
int missingElements = 10;
if(endbox) {
missingElements -= 1; // this means missingElements = missingElements - 1;
}
// etc