How do I ask the user to "play again" and rerun the do while loop with a simple yes or no question?

huangapple go评论175阅读模式
英文:

How do I ask the user to "play again" and rerun the do while loop with a simple yes or no question?

问题

import java.util.Scanner;
import java.util.Random;

public class HiLo {
    public static void main(String[] args) {
        Random random = new Random();
        Scanner input = new Scanner(System.in);
        final int MAX = 100;
        int answer = random.nextInt(MAX) + 1;
        int guess = -1;
        int numberOfGuesses = 0;
        String cont;

        System.out.println("猜一个1到" + MAX + "之间的数字: ");

        do {
            while (guess != answer) {
                numberOfGuesses++;
                guess = input.nextInt();

                if (guess == 101) {
                    break;
                } else if (guess > answer) {
                    System.out.println("太高了");
                    System.out.println("\n再猜一次: ");
                } else if (guess < answer) {
                    System.out.println("太低了");
                    System.out.println("\n再猜一次: ");
                } else {
                    System.out.println("正确! 数字是 " + answer + "。");
                    System.out.println("你用了 " + numberOfGuesses + " 次猜对了。");
                }
            }
            
            System.out.println("\n你想再玩一次吗 (yes/no)?");
            cont = input.nextLine();
        } while (cont.equals("yes"));
        
        input.close();
    }
}
英文:

So I added the yes or no statement prints out but it doesn't allow the user to type it in. How do I fix that and can I nest a while loop inside a do-while loop?

import java.util.Scanner;
import java.util.Random;

public class HiLo {
    public static void main(String[] args) {
        Random random = new Random();
        Scanner input = new Scanner(System.in);
        final int MAX = 100;
        int answer = random.nextInt(MAX) + 1;
        int guess = -1;
        int numberOfGuesses = 0;
        String cont;

        System.out.println(&quot;Guess a number between 1 and &quot; + MAX + &quot;: &quot;);

        do {
            while (guess != answer) {
                numberOfGuesses++;
                guess = input.nextInt();

                if (guess == 101) {
                    break;
                } else if (guess &gt; answer) {
                    System.out.println(&quot;Too High&quot;);
                    System.out.println(&quot;\nGuess again &quot;);
                } else if (guess &lt; answer) {
                    System.out.println(&quot;Too Low&quot;);
                    System.out.println(&quot;\nGuess again: &quot;);
                } else {
                    System.out.println(&quot;Correct! The number was &quot; + answer + &quot;.&quot;);
                    System.out.println(&quot;It took you &quot; + numberOfGuesses + &quot; guesses.&quot;);
                }
            }
            
            System.out.println(&quot;\nWould you like to play again (yes/no)?&quot;);
            cont = input.nextLine();
        } while (cont.equals(&quot;yes&quot;);
        
        input.close();
    }
}

答案1

得分: 1

好的,以下是您提供的代码的翻译:

import java.util.Scanner;
import java.util.Random;

public class Main{

     public static void main(String []args){

        Random random = new Random();
        Scanner input = new Scanner(System.in);
        final int MAX = 100;

        System.out.println("猜一个介于1到" + MAX + "之间的数字:");
        String cont = new String();
        do {
            System.out.println("让我们开始游戏");
            // 这里进行初始化
            int answer = random.nextInt(MAX) + 1;
            int guess = -1;
            int numberOfGuesses = 0;

            while (guess != answer) {
                numberOfGuesses++;
                guess = input.nextInt();

                if (guess == 101) {
                    break;
                } else if (guess > answer) {
                    System.out.println("太高了");
                    System.out.println("\n再次猜测");
                } else if (guess < answer) {
                    System.out.println("太低了");
                    System.out.println("\n再次猜测:");
                } else {
                    System.out.println("正确!数字是" + answer + "。");
                    System.out.println("你猜了" + numberOfGuesses + "次。");
                }
            }

            System.out.println("\n你想再玩一次吗(是/否)?");
            input.nextLine(); // 必须进入下一行...
            cont = input.nextLine();
        } while (cont.equals("是"));
        System.out.println("\n谢谢参与游戏!");
        input.close();
     }
}
英文:

Well, as I look to your looping logic it could be maintained and working as charm, you just need to move the initialization steps from the outside, to the inside do-while loop, in the beginning.

That way, at each start of the game, everything will work.

Also you're forgetting to go to next line before reading the user choice of yes/no, as you were reading just ints, at the end your a line ahead of the line containing the verdict yes/no

I tried this code in an online compiler, and it's working :

import java.util.Scanner;
import java.util.Random;

public class Main{

     public static void main(String []args){

        Random random = new Random();
        Scanner input = new Scanner(System.in);
        final int MAX = 100;

        System.out.println(&quot;Guess a number between 1 and &quot; + MAX + &quot;: &quot;);
        String cont = new String();
        do {
            System.out.println(&quot;Let&#39;s play&quot;);
            //Initializations here
            int answer = random.nextInt(MAX) + 1;
            int guess = -1;
            int numberOfGuesses = 0;


            while (guess != answer) {
                numberOfGuesses++;
                guess = input.nextInt();

                if (guess == 101) {
                    break;
                } else if (guess &gt; answer) {
                    System.out.println(&quot;Too High&quot;);
                    System.out.println(&quot;\nGuess again &quot;);
                } else if (guess &lt; answer) {
                    System.out.println(&quot;Too Low&quot;);
                    System.out.println(&quot;\nGuess again: &quot;);
                } else {
                    System.out.println(&quot;Correct! The number was &quot; + answer + &quot;.&quot;);
                    System.out.println(&quot;It took you &quot; + numberOfGuesses + &quot; guesses.&quot;);
                }
            }

            System.out.println(&quot;\nWould you like to play again (yes/no)?&quot;);
            input.nextLine();//You have to go to the next line...
            cont = input.nextLine();
        } while (cont.equals(&quot;yes&quot;));
        System.out.println(&quot;\nThanks for playing !&quot;);
        input.close();
     }
}

答案2

得分: 0

import java.util.Scanner;
import java.util.Random;

public class HiLo implements Runnable {
    private static boolean DEBUG = true; // Disable to not show the answer...
    private static final int MAX_NUMBER = 100;
    private static final int MAX_GUESSES = 5;
    private static final String YES = "YES";

    private final Random rand;

    public HiLo() {
        this.rand = new Random(System.currentTimeMillis());
    }

    public static void main(String[] args) {
        new Thread(new HiLo()).start();
    }

    @Override
    public void run() {
        Scanner scan = new Scanner(System.in);
        String cont = "";
        do {
            play(scan);
            System.out.print("\nWould you like to play again (yes/no)? ");
            cont = scan.nextLine();
            System.out.println();
        } while (cont.equalsIgnoreCase(YES));
        scan.close();
    }

    public void play(Scanner scan) {
        boolean correct = false;
        int numberOfGuesses = 0;
        int answer = rand.nextInt(MAX_NUMBER) + 1;

        if (DEBUG) System.out.printf("The answer is: %d%n", answer);

        System.out.printf("Guess a number between 1 and %d%n", MAX_NUMBER);

        while (numberOfGuesses < MAX_GUESSES && !correct) {
            numberOfGuesses++;
            correct = makeGuess(scan, answer, numberOfGuesses);
        }

        if (numberOfGuesses <= MAX_GUESSES && correct) {
            System.out.printf("Correct! The number was %d. It took you %d guesses.%n", answer, numberOfGuesses);
        } else {
            System.out.printf("Sorry, but you did not guess: %d", answer);
        }
        scan.nextLine(); // Reset...
    }

    public boolean makeGuess(Scanner scan, int answer, int currentGuesses) {
        System.out.print("Guess: ");
        int guess = scan.nextInt();

        if (guess == answer) {
            return true;
        }

        if (currentGuesses < MAX_GUESSES) {
            if (guess > answer) {
                System.out.print("Too High, ");
            } else {
                System.out.print("Too Low, ");
            }
        }

        return false;
    }
}

Sample Output:

The answer is: 64
Guess a number between 1 and 100
Guess: 50
Too Low, Guess: 75
Too High, Guess: 60
Too Low, Guess: 65
Too High, Guess: 64
Correct! The number was 64. It took you 5 guesses.
Would you like to play again (yes/no)? yes
The answer is: 88
Guess a number between 1 and 100
Guess: 50
Too Low, Guess: 90
Too High, Guess: 80
Too Low, Guess: 85
Too Low, Guess: 87
Sorry, but you did not guess: 88
Would you like to play again (yes/no)? no
英文:

I would organize this into a class with methods first. This breaks down each piece of logic and makes it easier to read.

  1. Start a "play" loop
  2. Inside the "play" loop, have a "guess" loop
  3. Store the "continue" state in a known constant
  4. Only check if they are correct after they made the max number of guesses.
  5. Seed the Random object with the current system time

Also, I added a DEBUG flag to display the answer.

Update: The program is ignoring or not even asking for your "yes" input, because you were previously asking it for integers. You will need to clear/flush/reset the scanner's buffer by calling nextLine. Switching from integer to string leaves some data in the buffer. So your program will use the left-over character data in the buffer before it prompts you for your input.

import java.util.Scanner;
import java.util.Random;

public class HiLo implements Runnable {
    private static boolean DEBUG = true; // Disable to not show the answer...
    private static final int MAX_NUMBER = 100;
    private static final int MAX_GUESSES = 5;
    private static final String YES = &quot;YES&quot;;

    private final Random rand;

    public HiLo() {
        this.rand = new Random(System.currentTimeMillis());
    }

    public static void main(String[] args) {
        new Thread(new HiLo()).start();
    }

    @Override
    public void run() {
        Scanner scan = new Scanner(System.in);
        String cont = &quot;&quot;;
        do {
            play(scan);
            System.out.print(&quot;\nWould you like to play again (yes/no)? &quot;);
            cont = scan.nextLine();
            System.out.println();
        } while (cont.equalsIgnoreCase(YES));
        scan.close();
    }

    public void play(Scanner scan) {
        boolean correct = false;
        int numberOfGuesses = 0;
        int answer = rand.nextInt(MAX_NUMBER) + 1;

        if (DEBUG) System.out.printf(&quot;The answer is: %d%n&quot;, answer);

        System.out.printf(&quot;Guess a number between 1 and %d%n&quot;, MAX_NUMBER);

        while (numberOfGuesses &lt; MAX_GUESSES &amp;&amp; !correct) {
            numberOfGuesses++;
            correct = makeGuess(scan, answer, numberOfGuesses);
        }

        if (numberOfGuesses &lt;= MAX_GUESSES &amp;&amp; correct) {
            System.out.printf(&quot;Correct! The number was %d. It took you %d guesses.%n&quot;, answer, numberOfGuesses);
        } else {
            System.out.printf(&quot;Sorry, but you did not guess: %d&quot;, answer);
        }
        scan.nextLine(); // Reset...
    }

    public boolean makeGuess(Scanner scan, int answer, int currentGuesses) {
        System.out.print(&quot;Guess: &quot;);
        int guess = scan.nextInt();

        if (guess == answer) {
            return true;
        }

        if (currentGuesses &lt; MAX_GUESSES) {
            if (guess &gt; answer) {
                System.out.print(&quot;Too High, &quot;);
            } else {
                System.out.print(&quot;Too Low, &quot;);
            }
        }

        return false;
    }
}

Sample Output

The answer is: 64
Guess a number between 1 and 100
Guess: 50
Too Low, Guess: 75
Too High, Guess: 60
Too Low, Guess: 65
Too High, Guess: 64
Correct! The number was 64. It took you 5 guesses.

Would you like to play again (yes/no)? yes

The answer is: 88
Guess a number between 1 and 100
Guess: 50
Too Low, Guess: 90
Too High, Guess: 80
Too Low, Guess: 85
Too Low, Guess: 87
Sorry, but you did not guess: 88

Would you like to play again (yes/no)? no

huangapple
  • 本文由 发表于 2020年4月8日 01:22:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/61085747.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定