我有一个 while(notFound)
循环。此循环首先检查选项“a”中指定的内容,但是循环中的某个点该选项变为“b”,在这种情况下,我需要将循环更新为:
while((notFound) &&(trCollator.compare(data.getSurname("a"),current.data().getSurname("a")) == 0))
那么是否有任何语法仅在选项等于“b”时才检查第二部分?
答案 0 :(得分:0)
您可以执行以下操作:
while((notFound)){
if(option.equals("a") || (option.equals("b") &&(trCollator.compare(data.getSurname("a"),current.data().getSurname("a")) == 0))){
//execute code...
}
}
答案 1 :(得分:0)
您可以使用布尔含义来处理附加条件:
»*If ... then ...*« 与 !... || ...
相同。
String option = "a";
while (notFound && (!"b".equals(option) ||
trCollator.compare(data.getSurname("a"), current.data().getSurname("a")) == 0))
{
// do stuff
}
答案 2 :(得分:0)
只需使用一个标志,说明您是否需要检查它。
boolean flag = false;
while (notFound &&
(!flag || trCollator.compare(data.getSurname("a"),current.data().getSurname("a") == 0)) {
...
if (somethingOrOther)
flag = true;
...
}
最初,flag
为假,因此!flag
为真,因此跳过逻辑或运算符的第二个子句。稍后,!flag
为假,因此计算第二个子句。
答案 3 :(得分:0)
// create an interface
public interface myInterface {
public boolean compareTo();
}
// create two classes
public class aa implements myInterface {
@Override
public boolean compareTo() {
// TODO Auto-generated method stub
return true;
}
}
public class bb implements myInterface {
String surname;
String currentSurname;
bb(String surname, String currSurname) {
this.surname = surname;
this.currentSurname = currSurname;
}
@Override
public boolean compareTo() {
// TODO Auto-generated method stub
return this.surname.equals(this.currentSurname);
}
}
// in while loop when you hit some condition change the value of mObj like below
Scanner n = new Scanner(System.in);
int tmp =n.nextInt();
myInterface mObj = new aa();
while(tmp > 0 && mObj.compareTo()) {
// some condition
if(tmp == 5) {
mObj = new bb("kumar", "sharma");
}
tmp--;
System.out.println(tmp);
}
System.out.println("Done");