繁体   English   中英

我怎样才能完成我的猜数游戏?

[英]How can I complete my number guessing game?

我的程序应该执行以下步骤:

  1. 生成从 0 到 100 的随机数。
  2. 显示随机数并要求用户输入(h/l/c) ? (用户必须输入其中之一)。
  3. 如果正确,请询问用户是否想再次玩(y/n) (用户必须回答(y/n) )

我能够执行问题 1。 问题 2,随机不显示但我无法输入字符(h/l/c) 另外,我不能问玩家他们是否想再玩一次?

这是我所做的:

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


public class NumberGuessingGame {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);

        int number;
        int guess = 0;
        int min = 0;
        int max = 100;
        int answer= (min+max);

        number = (int) (Math.random() *100 +1);
        System.out.println("Guess a number between 1 and 100.");

        //Ask user to type higher 'h', lower 'l' and correct 'c'.
        System.out.println("Is it " + number + " ?" + " (h/l/c): " );

        //
        guess = 50;

        while (guess <= 7)
        {
            System.out.println( "It is: " + guess + "?" + "(h/l/c) : " );

            //Type 'h' if guess is high, 'l' for low and 'c' for correct. 
            if(answer == 'h')
            {
                max = guess -1;
                min = 0;
                guess = ((max = min)/2) + min;
                guess++;

            } else if (answer == 'l')
            {
                max = 100;
                min = guess + 1;
                guess = ((max+min)/2);
                guess++;
            } else if (answer == 'c');
        }
        System.out.println("Great! Do you want to play again? (y/n): ");

        if(answer == 'y')
        {
            System.out.println("Guess a number between 1 and 100.");
            //else prompt another question with if else
        } else{
             System.exit(0);
        }
    }
}

您的程序不接受任何关于猜测值是太低还是太高的用户输入。

你用一个方程声明了“答案”,所以它应该接受一个数字。 answer 需要一个字符或字符串值。

answer = keyboard.nextChar(); //read a char
answer = keyboard.nextLine(); //read a String

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM