我被困在你需要从ArrayList中选择一个随机引用的位置,如果用户说“是”,则再次循环。
我应该使用任何for-loop或while循环还是什么? 请让我知道我应该朝哪个方向前进。
以下是我到目前为止所做的事情:
while (userGuess != numToGuess) {
if (userGuess < numToGuess) {
System.out.println("too low; try again");
userGuess = s.nextInt();
} else if (userGuess > numToGuess) {
System.out.println("too high; try again");
userGuess = s.nextInt();
} else {
System.out.println("wrong; try again!");
userGuess = s.nextInt();
}
}
答案 0 :(得分:2)
import java.util.Scanner;
强制执行此操作并添加更改代码,如下所示
public void guessMyNumber()
{
Random r = new Random();
numToGuess = r.nextInt(MAX) + 1;
Scanner input = new Scanner(System.in);
String answer;
do{
System.out.println("Please guess a number between 1 and 10");
userGuess = s.nextInt();
while(userGuess != numToGuess)
{
if(userGuess < numToGuess)
{
System.out.println("too low; try again");
userGuess = s.nextInt();
}
else if(userGuess > numToGuess){
System.out.println("too high; try again");
userGuess = s.nextInt();
}
else{
System.out.println("wrong; try again!");
userGuess = s.nextInt();
}
}
System.out.println("Congratulations! You've won a quotation.");
System.out.println("Do you want to continue ?(Yes/No)");
System.out.println("Quotation is :"+numbersget(r.nextInt(numbers.size())));
answer=input.next();
}while((answer.equalsIgnoreCase("Yes"))
}
这应该这样做。
答案 1 :(得分:1)
一种简单的方法是将数组作为list.toArray()从列表中取出。 然后在数组大小上使用Math.Random随机选择数组索引并使用它来选择随机引用。
答案 2 :(得分:0)
public static void guessMyNumber()
{
Random r = new Random();
String playAgain="Yes";
while(playAgain.equalsIgnoreCase("Yes")){
numToGuess = r.nextInt(MAX) + 1;
System.out.println("Please guess a number between 1 and 10");
userGuess = s.nextInt();
while(userGuess != numToGuess)
{
if(userGuess < numToGuess)
{
System.out.println("too low; try again");
userGuess = s.nextInt();
}
else if(userGuess > numToGuess){
System.out.println("too high; try again");
userGuess = s.nextInt();
}
else{
System.out.println("wrong; try again!");
userGuess = s.nextInt();
}
}
System.out.println("Congratulations! You've won a quotation.");
System.out.println("Quotation is :"+numbers.get(r.nextInt(numbers.size())));
System.out.println("play again? Yes or No?");
playAgain = s.next();
}
}
答案 3 :(得分:0)
你想在这里实现什么目标?
if(userGuess < numToGuess)
{
System.out.println("too low; try again");
userGuess = s.nextInt();
}
else if(userGuess > numToGuess){
System.out.println("too high; try again");
userGuess = s.nextInt();
}
else{
System.out.println("wrong; try again!");
userGuess = s.nextInt();
}
如果userGuess
小于numToGuess
,则说它“太低”,如果它更大,则说“太高”。如果它是平等的,你会说“错误;再试一次”。穷人会做什么? :P
对于它的价值......最后的其他情况永远不会发生(并且应该被删除)因为如果userGuess == numToGuess
你不会进入while循环。