方法体

时间:2016-08-27 22:56:53

标签: java methods infinite do-loops

请你帮忙解决一下为什么方法正文中的语句会无限循环?

我创建了一个班级Guesser。输入作为main()方法中的整数从用户获取,并确定答案为在main()方法中确定的整数。

该方法本身旨在验证用户输入的猜测参数与确定的答案(即5)并将输出返回到控制台“你错了......”或“正确!”。

因此,无论何时插入5,它都可以正常工作,只有一个问题,看起来输入的值会被传递给方法两次。并且它产生了一个问题,因为每当我输入4时,结果都被正确验证,并且在控制台中生成的输出返回正确的语句,但随后传递该值并再次返回,在循环中捕获无限返回相同的语句。

以下是代码:

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

2 个答案:

答案 0 :(得分:0)

您的循环中没有任何一点是等待用户输入数字,并将该数字存储在this.guess中。相反,你继续循环,直到他们的原始猜测变得正确。当然,这绝不会发生。

答案 1 :(得分: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();
}