Inf*_*lsx 3 java arrays random
我最近做了一个快速程序,让计算机猜出你输入的数字.我只是用它来向朋友展示一个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.");
}
Run Code Online (Sandbox Code Playgroud)
您可能想要使用ArrayList(动态增加的数组)
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(num);
Run Code Online (Sandbox Code Playgroud)
如果您想查看该号码是否已添加到arraylist中
if(list.contains(num))
{
System.out.println("You already tried " + num);
}
Run Code Online (Sandbox Code Playgroud)
A Set也是一个相当好的选择.它与a相同ArrayList但不允许重复.
HashSet<Integer> set = new HashSet<Integer>();
set.add(num);//returns true if the num was not inserted before else return false
if(!set.add(num))//set also has a contains method
{
System.out.println("You already entered " + num);
}
Run Code Online (Sandbox Code Playgroud)