Pet*_*ter 0 java iteration arraylist
我正在迭代一个ArrayList名为clientList的客户端,其中包含来自该类的客户端Client (user,pass)
ArrayList<Client> clientList= new ArrayList<Client>();
Run Code Online (Sandbox Code Playgroud)
这是迭代.如果它找到给定的用户(用户)并且密码(pass)匹配,我想停止迭代:
for (Client c : clientList) {
userA = c.getUser();
if (userA.equals(user)) {
passA = c.getPassword();
if (passA.equals(pass)) {
loginOK = true;
found= true;
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试以下(找到== false),但如果它没有在ArrayList上找到用户,它会被卡住:
while (found == false) { /
for (Client c : clientList) {
userA = c.getUser();
if (userA.equals(user)) {
passA = c.getPassword();
if (passA.equals(pass)) {
loginOK = true;
found= true;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
break找到值时,您应该退出循环.
for (something) {
if (anotherThingIsFound) {
break;
}
}
//Execution will continue here when you break...
Run Code Online (Sandbox Code Playgroud)
请注意,借助标签,也可以打破嵌套循环.例如
outer:
while (someCondition) {
for (criteria) {
if (somethingHappened) {
break outer;
}
if (anotherThingHashHappened) {
break;
}
}
//Execution will continue here if we execute the "normal" break.
}
//Execution will continue here when we execute "break outer;"
Run Code Online (Sandbox Code Playgroud)
continue 也适用于标签.
为什么不break呢?
for (Client c : clientList) {
userA = c.getUser();
if (userA.equals(user)) {
passA = c.getPassword();
if (passA.equals(pass)) {
loginOK = true;
found = true;
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
(我假设你需要告诉获取到年底之间的差别发现有人和获取到底,不找人,你可能只需要一个变量虽然,而不是两个...)
有了您的while循环尝试,你会在整个列表迭代永远如果用户没有找到,并且即使用户被发现,它会遍历整个列表一次-因为你的for循环是内 while循环.while循环每次迭代只检查while条件.