简体   繁体   English

是否可以在while循环中分配变量?

[英]Is it possible to assign a variable in a while loop?

I'm looking for a way to use scanner in a while loop, without advancing twice.我正在寻找一种在 while 循环中使用扫描仪而不前进两次的方法。

String desc = "";
while (!scanner.next().equals("END")) {
    desc = desc + scanner.next();
}           

As you can see, when scanner.next() is called in the while loop's condition and inside of the while loop itself.如您所见,当在 while 循环的条件中和 while 循环本身内部调用scanner.next()时。 I want it to advance the scanner only once.我希望它只推进扫描仪一次。 Is there any way to do that?有没有办法做到这一点?

Yes it is possible.是的,这是可能的。 You should also check that the Scanner has more tokens in its input您还应该检查Scanner的输入中是否有更多令牌

String desc = "";
String next = null;
while (scanner.hasNext() && !(next = scanner.next()).equals("END")) {
    desc = desc + next;
}
    String temp = "";
    do {
        desc = desc + temp;
        temp = scanner.next();
    } while(!temp.equals("END"))

You can use a do-while for post loop condition checking您可以使用 do-while 进行循环后条件检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM