我一直试图让最后的if语句执行,但我没有成功,任何输入都会有帮助
import java.util.Scanner; // Imports the Scanner class for keyboard input.
import java.util.Random; // Imports the Random class to generate a random number.
public class GuessingGameEC {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random ran = new Random();
int randomNum = ran.nextInt(501);
int Guess = 0;
Scanner keyboard = new Scanner(System.in);
for (int numOfTries = 0; numOfTries <10; numOfTries++) {
{
System.out.println(" " );
System.out.println("Guess what number I'm thinking of between 0 and 500.");
Guess = keyboard.nextInt();
if (Guess == randomNum) {
System.out.println("You guessed the correct number, and it only took you " + numOfTries + " tries." );
break;
}
else if (Guess < randomNum && Guess < 500 && Guess >= 0 && numOfTries != 10) {
System.out.println("Your guess is too low, please try again!" );
}
else if (Guess > randomNum && Guess <= 500 && numOfTries != 10) {
System.out.println("Your guess is too high, please try again!" );
}
else if (Guess > 500 || Guess < 0 ) {
System.out.println("Please pick a number between 0 and 500!" );
}
else if (numOfTries == 10) {
System.out.println(" " );
System.out.println("Sorry, you're out of attempts. The correct number was " + randomNum +"!" );
}
}
}
}
}
答案 0 :(得分:0)
当for
&gt; = 10时,您的numOfTries
循环条件会终止。您应该将最后一段代码放在for
循环之外。
答案 1 :(得分:0)
当您的for
循环从0变为9时,numOfTries == 10
的情况永远不会发生。
我会更改您的代码,以便您在成功时返回
if (Guess == randomNum) {
System.out.println("You guessed the correct number, and it only took you " + numOfTries + " tries." );
return;
}
然后在循环结束后,您可以无条件地打印失败的