好吧,我需要用java编写一个程序,它基本上是一个随机数生成器,玩家需要猜测生成了什么数字,从1到10。
我已经获得了代码,一切都工作得很好(代码发布在下面),但我想让用户不能两次使用相同的号码。
例如,玩家输入 2,然后输入 3,然后再次输入 2。我想要它 return “您已经输入了这个号码” 对于我的一生,我无法让它发挥作用。
我一直在尝试使用 HashSets,因为我相当确定该方法是正确的方法,但是当涉及到调用 HashSet 中已有的数字以及它们是否在HashSet 已经返回“您已经输入了这个数字”。
我尝试修改
if (hs.contains(guess)) == true)
System.out.println("You have already entered this number")
我还输入了hs.add(guess)
并猜测玩家输入的数字。我真的很困惑,如果你们能引导我走向正确的方向,我将不胜感激。
非常感谢高级
package guessgame;
import java.util.HashSet;
import java.util.Scanner;
public class GuessGame {
public static void main(String[] args) {
HashSet<Integer>hs = new HashSet();
int GuessLogic;
GuessLogic = (int) (Math.random() * 10 + 1);
Scanner keyboard = new Scanner (System.in);
int guess;
int NumGuess;
NumGuess = 1;
do {
System.out.print("Enter a guess: ");
guess = keyboard.nextInt();
System.out.println("Your guess is " + guess);
if (guess == GuessLogic)
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + NumGuess++);
else if (guess < GuessLogic && guess > 0)
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + NumGuess++);
else if (guess > GuessLogic && guess <= 10)
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + NumGuess++);
else
System.out.println("Your guess is out of the specified range. Please try again." );
} while (guess != GuessLogic);
}
}
最佳答案
首先,您应该对接口(interface)进行编程 Set
(而不是具体类型HashSet
)。接下来,您可以使用Set.add(E)
如果此集合尚未包含指定元素,则返回true
。。最后,我建议使用有意义的变量名称。把它们放在一起,它可能看起来像,
Set<Integer> hs = new HashSet<>();
int correctNumber = 1 + (int) (Math.random() * 10);
Scanner keyboard = new Scanner(System.in);
int guessCount = 1;
int guess;
do {
System.out.print("Enter a guess: ");
guess = keyboard.nextInt();
System.out.println("Your guess is " + guess);
if (hs.add(guess)) {
if (guess == correctNumber) {
System.out.println("You got it right!! Congrats!! Total Number of "
+ "Guesses: " + guessCount++);
} else if (guess < correctNumber && guess > 0) {
System.out.println("You are wrong!!! Hint: Guess "
+ "Higher, Guess number: " + guessCount++);
} else if (guess > correctNumber && guess <= 10) {
System.out.println("You are wrong!!! Hint: Guess "
+ "Lower, Guess number: " + guessCount++);
} else {
System.out.println("Your guess is out of the specified range. "
+ "Please try again.");
}
} else {
System.out.println("You have already entered this number");
}
} while (guess != correctNumber);
关于java - 简单的Java方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35787303/