如何为此Guessing游戏创建for循环?

时间:2018-02-19 07:28:37

标签: java loops for-loop

我实在不知道怎么说这个,这就是为什么这些问题看起来有些奇怪或者像初学者一样。我正在为我的Java课程作业创建一个猜谜游戏,我在一个部分遇到了麻烦。

这是我到目前为止的整个代码:

import java.util.Random;
import java.util.*;

public class GuessingGame{ 

    public static void main(String args[]) 
    {

        System.out.println("Welcome to the greatest Guessing Game known to mankind!");
        System.out.println("-------------------------------------------------------\n");
        System.out.println("You will be guessing what number I am guessing by entering your guess.");
        System.out.println("The number will be between 1 to 100\n");

        Scanner start = new Scanner(System.in);
        System.out.println("Do you want to start the game?(1 for Yes, 2 for fun facts before starting the game!)\n");
        int getStart = start.nextInt();

        // testing random number generator
        //System.out.println(Math.random() * 100);

        if(getStart == 1)
        {
            Process();
        }

    }

    public static void Process ()
    {
        int max = 100;
        int min = 1;

        Random ranNum = new Random();
        int ActualNum = min + ranNum.nextInt(max);
        System.out.println(ActualNum);

        //for(int i = getGuess; i == ActualNum; i++)
        //{
        Scanner guess = new Scanner(System.in);
        System.out.println("\nI am thinking of a number...");
        System.out.println("What's your guess?\n");
        int getGuess = guess.nextInt();

        if (getGuess < ActualNum)
        {
            System.out.println("Higher!");
        }

        if (getGuess == ActualNum)
        {
            System.out.println("\nCorrect! You've won!");
        }   
        //}

    }
}

正如你所看到的,我评论了For循环部分,但我试图创建一个for循环,所以它得到getGuess,这是用户输入,直到用户得到它正确。我希望它继续给予猜测更高!&#34;或者&#34;猜得更低!&#34;每当用户输入一个数字而不运行一次并完成程序时提示。

谢谢,我希望我说问题的方式有道理。我是一个需要帮助的初学者。 :)

顺便说一下:我知道我正在打印他们猜测的数字。我只是在测试一些东西。

2 个答案:

答案 0 :(得分:0)

尝试做这样的事情

    int getGuess = 0;

    while (getGuess != actualNum) {

        System.out.println("What's your guess?\n");
        Scanner guess = new Scanner(System.in);
        getGuess = guess.nextInt();


        if (getGuess < actualNum) {
            System.out.println("Higher!");
        }

        if (getGuess == actualNum) {
            System.out.println("\nCorrect! You've won!");
        }
    }

输出如下: Output of the program

答案 1 :(得分:0)

执行此操作的一种简单方法是更改​​getGuess变量的范围并使用while循环。这样,您可以在每次尝试进入循环时检查该值。将值初始化为不进行检查的值(例如0,因为这不在[1,100]中)。

[...]
int getGuess = 0;
Scanner guess = new Scanner(System.in);

while(getGuess != ActualNum)
{
    System.out.println("\nI am thinking of a number...");
    System.out.println("What's your guess?\n");
    getGuess = guess.nextInt();

    if (getGuess < ActualNum)
    {
        System.out.println("Higher!");
    }

    if (getGuess == ActualNum)
    {
        System.out.println("\nCorrect! You've won!");
    }
}
[...]