如果work.length
为4,
我必须检查AResult
in for循环
如果4个AResult都是true
,请设置result.setstatus("success");
或result.setstatus("fail");
我该怎么办?
for(int i = 0;i < work.length;i++){
if(!work[i].contains("#")){
CommandLineInterface CLI = new CommandLineInterface();
String IP = null;
boolean AResult;
try {
AResult = CLI.Setting(work[i],"start"); //true or false
} catch (JSchException | InterruptedException e) {
e.printStackTrace();
}
}
}
//result.setstatus("success"); //all true
//result.setstatus("fail");
答案 0 :(得分:1)
添加一个计数器。当条件为true
时递增它。循环后检查counter
的值。像
int counter = 0;
for(int i = 0;i < work.length;i++){
if(!work[i].contains("#")){
CommandLineInterface CLI = new CommandLineInterface();
String IP = null;
boolean AResult;
try {
AResult = CLI.Setting(work[i],"start");
if (AResult) {
counter++;
}
} catch (JSchException | InterruptedException e) {
e.printStackTrace();
}
}
}
if (work.length == 4 && counter == 4) {
result.setstatus("success");
} else {
result.setstatus("fail");
}
您可以使用类似
的内容优化上述(并减小代码大小)int counter = 0;
if (work.length == 4) { // <-- check the length first
for (int i = 0; i < work.length; i++) {
if (!work[i].contains("#")) {
CommandLineInterface CLI = new CommandLineInterface();
try {
if (CLI.Setting(work[i], "start")) {
counter++; // <-- increment the counter.
} else {
break; // <-- break on any fale.
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
result.setstatus(counter == 4 ? "success" : "fail"); // <-- setstatus
答案 1 :(得分:0)
试试这个,你真的不需要迭代循环直到结束时遇到错误的条件
//initially set success
result.setstatus("success");
for(int i = 0;i < work.length;i++){
if(!work[i].contains("#")){
CommandLineInterface CLI = new CommandLineInterface();
String IP = null;
try {
if(CLI.Setting(work[i],"start"))
{
result.setstatus("fail");
//no need to iterate further
break;
}
} catch (JSchException | InterruptedException e) {
e.printStackTrace();
}
}
}
答案 2 :(得分:0)
您还可以尝试以下代码
boolean statusFlag = true;
for(int i = 0;i < work.length;i++){
if(!work[i].contains("#")){
CommandLineInterface CLI = new CommandLineInterface();
String IP = null;
boolean AResult;
try {
AResult = CLI.Setting(work[i],"start"); //true or false
if(!AResult){
statusFlag = false;
}
} catch (JSchException | InterruptedException e) {
e.printStackTrace();
}
}
}
if(statusFlag){
result.setstatus("success");
}else{
result.setstatus("fail");
}
}