【发布时间】:2016-02-10 06:37:56
【问题描述】:
我最近做了一个快速程序,让计算机猜你输入的数字。我只是用它来向朋友展示一个 While 循环的例子。我决定让它变得更复杂,但我不知道该怎么做。
我希望将每个随机猜测添加到一个数组中,这样它就不会多次猜测同一个数字。
Scanner scan = new Scanner (System.in); // Number to guess //
Random rand = new Random(); // Generates the guess //
int GuessNum = 0, RandGuess = 0;
System.out.println("Enter a number 1 - 100 for me to guess: ");
int input = scan.nextInt();
if (input >= 1 && input <= 100)
{
int MyGuess = rand.nextInt (100) + 1;
while ( MyGuess != input)
{
MyGuess = rand.nextInt (100) + 1;
GuessNum++;
}
System.out.println ("I guessed the number after " + GuessNum + " tries.");
}
【问题讨论】:
-
你不知道怎么办?
-
考虑集合而不是数组。这种情况(“以前是否遇到过这个值”)非常适合它。
-
到目前为止你做了哪些努力?
-
我会创建一个数组并通过 GuessNum 对其进行索引,然后我会使用另一个 while 循环来检查所有结果并查看它们是否已经完成。
-
对不起,我今天出去了。感谢您的回复,我将尝试看看我能做些什么!