出于某种原因,第一次执行do-while循环时,扫描程序要求输入两次

时间:2016-03-24 00:39:11

标签: java java.util.scanner

因为我创建了一种接受用户输入的方法,所以就是这样。之前,扫描仪处于循环中,但它导致了一个不同的小问题。我以前从未遇到过这个问题..

    public static int input(){

    Scanner scan = new Scanner (System.in);

    int guess;
    guess = scan.nextInt();
    return(guess);
}

    public static void main(String[] args) {

    do{ 
        if (firstPromptIsPrinted){
        System.out.println("Enter a number between 1 and 20.");
        }
        guess = input();

        if (secondPromptIsPrinted){
            System.out.println("Nope ;). ");
        } 
        if (secondPromptIsPrinted){
            giveHint(guess, luckyNumber);
        }
        firstPromptIsPrinted = false; //Now
        secondPromptIsPrinted = true;

    } while (guess != luckyNumber);

1 个答案:

答案 0 :(得分:0)

我重新组织它以摆脱静态输入法......这有效:我认为一个变化是围绕System.out.println的if条件(“Nope ...”); ...

public class GuessGame {

    Scanner scan = null;

    public GuessGame() {
        scan = new Scanner ( System.in );
    }

    public int input() {
        int ltheResult;
        ltheResult = scan.nextInt ();
        return ltheResult;
    }

    public static void main(String[] args) {
        GuessGame ltheClass = new GuessGame ();
        ltheClass.run ();
    }

    public void run () {
        int guess = 0;
        boolean firstPromptIsPrinted = true;
        boolean secondPromptIsPrinted = false;
        int luckyNumber = 10;

        do {
            if ( firstPromptIsPrinted ) {
                System.out.println ( "Enter a number between 1 and 20." );
            }
            guess = this.input ();

            if ( guess != luckyNumber ) {
                System.out.println ( "Nope ;). " );
            }
            // if (secondPromptIsPrinted){
            // giveHint(guess, luckyNumber);
            // }
            firstPromptIsPrinted = false; // Now
            secondPromptIsPrinted = true;

        }
        while ( guess != luckyNumber );
        System.out.println ( "Yes luckyNumber is [" + luckyNumber + "]" );
    }
}