Java에서 while 루프를 어떻게 종료합니까?
Java에서 while 루프를 종료 / 종료하는 가장 좋은 방법은 무엇입니까?
예를 들어, 내 코드는 현재 다음과 같습니다.
while(true){
if(obj == null){
// I need to exit here
}
}
사용 break
:
while (true) {
....
if (obj == null) {
break;
}
....
}
그러나 코드 가 지정한 것과 똑같은 경우 일반 while
루프를 사용하고 조건을 obj != null
다음 과 같이 변경할 수 있습니다 .
while (obj != null) {
....
}
while(obj != null){
// statements.
}
break
당신이 찾고있는 것입니다 :
while (true) {
if (obj == null) break;
}
또는 루프를 재구성하십시오.
while (obj != null) {
// do stuff
}
또는:
do {
// do stuff
} while (obj != null);
내 코드에서 while...do
구문을 찾으면 while(true)
눈이 피를 흘릴 것입니다. while
대신 표준 루프를 사용하십시오 .
while (obj != null){
...
}
그리고 Yacoby가 그의 답변 에서 제공 한 링크를 살펴보십시오 . 진지하게.
논리 검사와 동일한 규칙을 사용하여 while () 검사 내에서 여러 조건 논리 테스트를 수행 할 수 있습니다.
while ( obj != null ) {
// do stuff
}
작동합니다.
while ( value > 5 && value < 10 ) {
// do stuff
}
are valid. The conditionals are checked on each iteration through the loop. As soon as one doesn't match, the while() loop is exited. You can also use break;
while ( value > 5 ) {
if ( value > 10 ) { break; }
...
}
Take a look at the Java™ Tutorials by Oracle.
But basically, as dacwe said, use break
.
If you can it is often clearer to avoid using break and put the check as a condition of the while loop, or using something like a do while loop. This isn't always possible though.
You can use "break", already mentioned in the answers above. If you need to return some values. You can use "return" like the code below:
while(true){
if(some condition){
do something;
return;}
else{
do something;
return;}
}
in this case, this while is in under a method which is returning some kind of values.
if you write while(true). its means that loop will not stop in any situation for stop this loop you have to use break statement between while block.
package com.java.demo;
/**
* @author Ankit Sood Apr 20, 2017
*/
public class Demo {
/**
* The main method.
*
* @param args
* the arguments
*/
public static void main(String[] args) {
/* Initialize while loop */
while (true) {
/*
* You have to declare some condition to stop while loop
* In which situation or condition you want to terminate while loop.
* conditions like: if(condition){break}, if(var==10){break} etc...
*/
/* break keyword is for stop while loop */
break;
}
}
}
참고URL : https://stackoverflow.com/questions/7951690/how-do-i-exit-a-while-loop-in-java
'code' 카테고리의 다른 글
Java Swing-JScrollPane 사용 및 맨 위로 스크롤 (0) | 2020.10.18 |
---|---|
PHP read_exif_data 및 방향 조정 (0) | 2020.10.18 |
Gradle DSL 메서드를 찾을 수 없음 : 'compile ()' (0) | 2020.10.18 |
Apache Tomcat 서버의 명령 프롬프트에서 디버그 모드를 시작하는 방법은 무엇입니까? (0) | 2020.10.18 |
CSS를 사용하여 텍스트를 감싸는 방법은 무엇입니까? (0) | 2020.10.18 |