需要帮助在我的代码中添加一个playAgain循环

时间:2017-03-13 00:06:55

标签: loops while-loop user-input playback

该程序假设从用户那里获得2个号码。并将其指向高或低,顺序无关紧要。然后它将使计算机生成一个随机数,用户必须输入一个数字以查看它是否匹配。如果用户编号太低或太高,我的程序将显示。

我需要帮助的是在此代码中放置一个playAgain循环。应该说“你想再玩一次吗?(是/否)”。然后它将获取用户字符串或字符,并将再次运行程序或结束程序(取决于用户输入的内容)。

我一直在工作和研究它几个小时,似乎找不到方法(也许我是密集的大声笑)。对不起,如果我第二次发布这个问题,我需要在今天结束时完成这个。

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.");
            }
        }

    }
}

1 个答案:

答案 0 :(得分:0)

你需要围绕游戏主体进行第二次循环,询问延续问题。如果球员说不,你可以退出。查看Scanner的java doc,了解它可以读到的内容。