[英]Having trouble printing statement at the end of a for loop
我一直在嘗試執行其他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 +"!" );
}
}
}
}
}
當numOfTries
> = 10時,您的for
循環條件終止。您應將最后一個代碼塊置於for
循環之外。
當您的for
循環從0變為9時, numOfTries == 10
的情況將永遠不會發生。
我會更改您的代碼,以便成功時返回
if (Guess == randomNum) {
System.out.println("You guessed the correct number, and it only took you " + numOfTries + " tries." );
return;
}
然后在循環完成后,您可以無條件打印失敗
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.