需要帮助将游戏循环添加到我的代码中



此程序假设从用户获得2个数字。并将其定向为高或低,订单无关紧要。然后,它将导致计算机生成一个随机数,并且用户必须输入一个数字才能查看是否匹配。然后,我的程序将显示用户编号太低或太高。

我需要帮助的是将Playagain循环放入此代码中。它应该说"您想再次玩吗?(Y/N)。"然后,它将获得用户字符串或字符,并将再次运行程序或结束程序(取决于用户输入的内容)。

我已经工作了几个小时,似乎找不到方法(也许我很密集)。抱歉,如果我第二次发布了这个问题,我需要在今天结束时完成此问题。

import java.util.*;
/*
Guessing Game Group Project.  This game will ask for two numbers to set the range,
*/
public class Guess1
{
    public static void main(String [] args)
    {
        Scanner S = new Scanner(System.in);                                                                                                                             //Introduction Statement to game
        System.out.println("This is a guessing game.  I will ask you for two numbers.");
        System.out.println("I will choose a random number between your two numbers for you " + "n" + "to try and guess.  As you guess, I will give you hints.");
        System.out.print("Choose two numbers to bound your range: ");                                                                                                   //Scanner to store user's input for the range
        int u1 = S.nextInt();
        int u2 = S.nextInt();
        int guess;
        int count = 0; // = 0 new
        String playAgain;
        int high;
        int low;
        if(u1 < u2)
        {
            high = u2;
            low = u1;
        }
        else
        {
            high = u1;
            low = u2;
        }
        Random gen = new Random();
        int rand = gen.nextInt(high-low+1) + low;
        System.out.println("Now guess a number between " + low + " and " + high + ": ");
        guess = S.nextInt();
        while(guess != rand)
        {
            count++;
            if (guess > high || guess < low)
            {
                System.out.println("Out of range. Please follow the directions dumb-ass.");
            }
            else if(guess > rand)
            {
                high = guess;
                System.out.println("Too high!");
            }
            else
            {
                low = guess;
                System.out.println("Too low!");
            }
            System.out.print("Now guess a number between " + low + " and " + high + ": ");
            guess = S.nextInt();
            if(guess == rand)
            {
                System.out.println("You got it!");
            }
            else if(count == 10)
            {
                System.out.println("You lost! So Sorry.");
            }
        }
    }
}

您将需要在游戏主体周围进行第二个循环,以提出延续问题。如果玩家说不,您可以退出。查看扫描仪的Java Doc,以查看它可以阅读的内容。

相关内容

  • 没有找到相关文章

最新更新