我的RandomNumber值在for循环语句中发生了变化。这可以防止程序将生成的RandomNumber与用户输入的数字实际匹配。如何修改for循环以使其不影响RandomNumber?
这是我在NetBeans中所做的java代码;
package numberguess;
/**
*
* @author Marion
*/
public class NumberGuess {
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) {
int randNum = 0, guessNum = 0;
// Generates a random number from 1 to 10
randNum = new java.util.Random().nextInt(10) + 1;
System.out.println("I am thinking of a random number from 1 to 10");
for (randNum = 0; randNum < 3; randNum = randNum + 1) {
System.out.print("Guess?");
java.util.Scanner scan = new java.util.Scanner(System.in);
guessNum = scan.nextInt();
System.out.println("You guessed " + guessNum);
if (randNum == guessNum) {
System.out.println("You Guessed it!");
break;
}
}
}
}
答案 0 :(得分:6)
您必须使用其他变量来循环计数。你在
中分配给randNumfor (randNum = 0; randNum <3; randNum = randNum + 1)
答案 1 :(得分:3)
for (randNum = 0; randNum <3; randNum = randNum + 1)
更改为
for (int i= 0; i<3; i = i+ 1)
答案 2 :(得分:2)
此处:请注意我将扫描仪移到了循环外部,因为您不需要多次创建它。
public static void main(String[] args) {
int randNum = randNum = new java.util.Random().nextInt(10) + 1;
int guessNum = 0;
java.util.Scanner scanner = new java.util.Scanner(System.in);
System.out.println("I am thinking of a random number from 1 to 10");
for(int i =0; i < 3; i++) {
System.out.print("Guess?");
guessNum = scanner.nextInt();
if(randNum == guessNum) {
System.out.println("You Guessed it!");
break;
}
System.out.println("You guessed " + guessNum);
}
}
}
答案 3 :(得分:1)
我刚刚为for循环分配了另一个变量。
for (int rand1 = 0; rand1 <3; rand1 = rand1 + 1)
{
if (rand1 == guessNum)
{
System.out.println("You Guessed it!");
break;
}
}