在java中,是否可以向while循环中间循环插入新条件?

cgfeq70w  于 2021-08-20  发布在  Java
关注(0)|答案(4)|浏览(422)

我有一个 while(notFound) 环此循环首先检查选项“a”中指定的内容,但是循环中的某个点该选项变为“b”,在这种情况下,我需要将循环更新为: while((notFound) &&(trCollator.compare(data.getSurname("a"),current.data().getSurname("a")) == 0)) 那么,是否有语法只在选项等于“b”时才检查第二部分?

kuhbmx9i

kuhbmx9i1#

您可以执行以下操作:

while((notFound)){
  if(option.equals("a") || (option.equals("b") &&(trCollator.compare(data.getSurname("a"),current.data().getSurname("a")) == 0))){
          //execute code...
    }
}
gmxoilav

gmxoilav2#

您可以使用布尔蕴涵来处理附加条件:
»如果。。。那么…«这与 !... || ... .

String option = "a";
while (notFound && (!"b".equals(option) ||
       trCollator.compare(data.getSurname("a"), current.data().getSurname("a")) == 0))
{
  // do stuff
}
fquxozlt

fquxozlt3#

只需使用一个标志,表明您是否需要检查它。

boolean flag = false;
while (notFound &&
       (!flag || trCollator.compare(data.getSurname("a"),current.data().getSurname("a") == 0)) {

     ...
     if (somethingOrOther)
         flag = true;
     ...

}

最初,, flag 是假的,所以 !flag 为true,因此跳过逻辑or运算符的第二个子句。后来,, !flag 为false,因此对第二个子句进行求值。

nwo49xxi

nwo49xxi4#

// 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");

相关问题