なぜメソッド本体のステートメントが無限ループを続けているのか、私の頭を浮かべるのを助けてください。無限大メソッドのループ内でループする
私はクラス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
ループ内で 'answer1'または' guess'を変更することは決してありません。 – chrylis