2016-08-27 2 views
0

なぜメソッド本体のステートメントが無限ループを続けているのか、私の頭を浮かべるのを助けてください。無限大メソッドのループ内でループする

私はクラスGuesserを作成しました。入力は、main()メソッド内の整数としてユーザから取得され、main()メソッド内で決定された整数として回答を決定します。

メソッド自体は、ユーザーが入力した推測されたパラメータ(5)を検証し、コンソールに出力します。「間違っていますか...」か「修正してください」。

私は5を挿入するたびに、入力された値がメソッドに2回渡されたように見えますそして、私が入力するたびに結果が正しく検証され、コンソールで生成された出力が正しいステートメントを返しますが、値が何度も繰り返し渡され、同じステートメントを無限ループで返すように戻ります。あなたが番号を入力するようにユーザを待ち、そして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

こんにちは@Vlad。これは「3進」演算子です。一度理解すれば本当に役に立ちます。フォーマットは '' '条件ですか? true-result:false-result'''です。この場合、条件は「推測<答え」である。それが真であれば "low"を返し、System.out.println()は "low"で呼び出されます。そうでなければ "高"と呼ばれます – pmcevoy12

+0

それは確かです!どうもありがとう!それは今完璧な意味があります。 – Vlad