2016-08-27 8 views
0

메서드의 본문이 무한 반복되는 이유는 무엇입니까?무한 메소드의 몸체에 루프 수행

나는 Guesser 클래스를 만들었습니다. 입력은 main() 메쏘드 내의 정수로 사용자로부터 취해지고 main() 메쏘드 내에서 결정된 정수로서 답을 결정합니다.

방법 자체는 사용자가 입력 한 추측 된 매개 변수를 확인 된 값 (5 점)에 대해 유효성을 검사하고 "you 're wrong ..."또는 "Correct!"라는 콘솔로 출력을 반환하도록 설계되었습니다.

그래서 삽입 할 때마다 입력 된 값이 메서드에 두 번 전달되는 것처럼 보이는 한 가지 문제가 발생합니다. 그리고 입력 할 때마다 결과가 올바르게 검증되고 콘솔에서 생성 된 출력이 올바른 명령문을 반환하지만 값이 반복적으로 전달되어 동일한 문장을 무한히 반환하는 루프에서 잡히는 것처럼 문제가됩니다. 당신이 번호를 입력하도록 사용자 기다린 this.guess에 그 번호를 저장 않는 루프에 어떤 시점에서

import java.util.Scanner; 
//class begins here 
class Guesser { 
int answer1; 
int guess; 

//constructor 
Guesser(int ans, int gs) { 
    answer1 = ans; 
    guess = gs; 
} 

//Method starts here 
void method1() { 
//Do control statement comes here 
do { 
    System.out.println("Guess the number..."); 
    if(this.guess != this.answer1) { 
     System.out.print("Your guess is worng. You're too "); 
     if(this.guess < this.answer1) System.out.println("low"); 
     else System.out.println("high"); 
    } //end of if statement 
} while (this.guess != this.answer1); //end of Do Control Statement 
System.out.println("Correct!"); 
} //end of method1 
} //End of the class Guesser 

//Main class comes here 
public class DemoGuess { 

    public static void main(String args[]) { 
     System.out.println("Guess the number..."); 
     int input; 

     Scanner in = new Scanner(System.in); 
     input = in.nextInt(); 
     Guesser ActionGuess = new Guesser(5,input); 
     ActionGuess.method1(); 


    } //end of main() method 

} //end of DemoGuess class 
+1

루프 내부에서'answer1' 또는'guess'를 변경하는 일은 절대로하지 마십시오. – chrylis

답변

0

: 여기

는 코드입니다. 오히려, 원래 추측이 정확해질 때까지 루핑을 계속합니다. 물론, 결코 일어나지 않습니다.

0

새로운 추측 값을 얻으려면 루프 중에 입력을 읽고 입력해야합니다.

public void method1() { 
    Scanner input = new Scanner(System.in); 
    int guess = 0; 
    do { 
     System.out.println("Guess the number..."); 
     guess = input.nextInt(); // prompt user for a new guess 
     if (guess != answer) { 
      System.out.print("Your guess is wrong.\nYou are too "); 
      System.out.println((guess < answer) ? "low" : "high"); 
     } 
    } while (guess != answer); 
    System.out.println("Correct!"); 
    input.close(); 
} 
+0

수정 된 코드 pmcevoy에 감사드립니다! 이 문이 어떻게 작동하는지 명확하게 설명해 주시겠습니까? System.out.println ((추측 <답변)? "낮음": "높음") Java의 기본 사항을 선택하고 작성한이 문은 논리적 함수를 인쇄 줄 메서드 내에서하지만 난 그것을 잡는 게 아니에요. 많은 감사! – Vlad

+0

안녕하세요. 그것은 "삼항"연산자입니다. 일단 이해하면 정말 도움이됩니다. 형식은'''조건입니까? 참 - 결과 : 거짓 - 결과''. 이 경우 조건은 "추측 <대답"입니다. 이것이 사실이면 "낮음"을 반환하므로 System.out.println()이 "낮음"으로 호출됩니다. 그렇지 않으면 "high"라고합니다. – pmcevoy12

+0

실제로입니다! 매우 감사합니다! 그것은 이제 완벽하게 이해됩니다. – Vlad