2017-01-15 5 views
1

를 실행하면 루프가 계속 인쇄 나는이 내 프로그램에서 사용하는 다음 코드를마 - 동안 프로그램

, 실행할 때, 내가 한 번만 발생 할 방법을 반복 유지
do { 
    if (numOfItems == 3 || numOfItems == 5 || numOfItems == 7 || numOfItems == 9) { 
     addItems(numOfItems); 

    } else { 
     System.out.println("That number is out of range."); 
     System.out.println("Please choose an odd number in the range of [1, 10] exclusively:"); 
     numOfItems = scan.nextInt(); 
    } 
} while (numOfItems != 3 || numOfItems != 5 || numOfItems != 7 || numOfItems != 9); 

. 유효성 검사를 위해 루프를 반복하여 유지하는 방법은 없지만 메서드를 한 번만 실행하십시오. 당신은 다음과 같은 것을 할 필요가 같은

답변

3

while (numOfItems != 3 && numOfItems != 5 && numOfItems != 7 && numOfItems != 9);

업데이트 대답에 귀하의 코멘트에서

while (numOfItems != 3 || numOfItems != 5 || numOfItems != 7 || numOfItems != 9);

교체, 그것은 같습니다

do { 
    numOfItems = scan.nextInt(); 
    if (numOfItems == 3 || numOfItems == 5 || numOfItems == 7 || numOfItems == 9) { 
     addItems(numOfItems); 

    } else { 
     System.out.println("That number is out of range."); 
     System.out.println("Please choose an odd number in the range of [1, 10] exclusively:"); 

    } 
} while (numOfItems != 3 && numOfItems != 5 && numOfItems != 7 && numOfItems != 9); 

그러나, 당신은 다음과 같은 것을이를 최적화 할 수 있습니다 : 그것은 항상 사실 될 것이라고, 이후

while ((numOfItems = scan.nextInt() != 3) && numOfItems != 5 && numOfItems != 7 && numOfItems != 9) { 

      System.out.println("That number is out of range."); 
      System.out.println("Please choose an odd number in the range of [1, 10] exclusively:"); 
} 

addItems(numOfItems); 
+0

그러나 해결책을 수정했지만 이제는 올바르게 검증되지 않습니다. 3, 5, 7 또는 9가 아닌 숫자를 입력 한 다음 그 숫자 중 하나를 입력하면 방법이 실행되지 않습니까? – Kooba

+0

그게 바람직한 행동이 아니겠습니까? 사용자가이 4 개의 숫자 중 하나를 입력 할 때까지 루프를 계속 실행합니까? 이것이 바람직한 행동이 아니면 더 많은 설명을 제공해야합니다. – VHS

+0

@Kooba : "방법"은 무엇을 의미합니까? 제공 한 코드에서 어떤 메소드도 호출하지 않습니다. –

1

당신은

while (numOfItems != 3 || numOfItems != 5 || numOfItems != 7 || numOfItems != 9); 

를 해결 할 수 있습니다.

항상 do{...} 문장 블록을 실행하려면이 (do..while) 조건을 제거 할 수 있습니다. ("... 한 번만하고 싶다 ...")