-1
我的程序有問題。我有猜測遊戲的基礎知識,但我有一個問題根據猜測的數量實現不同的短語。目前,當程序運行並輸入一個數字時,它會立即移動到遊戲結束,並顯示答案,而不允許多次猜測。這是我的代碼。我已經編輯它被格式化的更好一點,因爲每個人都抱怨過:猜測遊戲 - 在While循環內嵌套if語句的問題
import java.util.*;
public class Hw_five {
public static void main(String[] args) {
int answer;
int tries = 0;
answer = (int) (Math.random() * 99 + 1);
System.out.println("Welcome to the Guess the Number Game ");
System.out.println("+++++++++++++++++++++++++++++++++++++ \n");
System.out.println("I'm thinking of a number between 1-100 ");
System.out.println("Try to guess it! ");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
int guess = getIntWithinRange(sc, "Please enter a number: ", 0, 100);
if (guess != answer) {
if (guess == answer) { System.out.println("Your guess is correct! Congratulations!");
}
else if (guess < answer)
{ System.out.println("Your guess was too low. Try again. ");
tries++;
}
else {System.out.println(
"Your guess was too high. Try again."); tries++; }
}
System.out.println("The number was " + answer + " !");
System.out.println("You guessed it in " + tries + " tries");
//ask if they want to continue
System.out.println("\n Continue (y/n)? ");
choice = sc.next();
System.out.println();
}
//print out thank you message
System.out.println("Thanks for playing! Try again later. ");
sc.close();
}
public static int getInt(Scanner sc, String prompt) {
int i = 0;
boolean valid;
valid = false;
while (valid == false)
{
System.out.println(prompt);
if (sc.hasNextInt()) {
i = sc.nextInt();
valid = true;
} else {
System.out.println("Please enter a number. ");
sc.next();
}
}
return i;
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
i = getInt(sc, prompt);
if (i <= min) {
System.out.println("Error! Number must be greater than " + min + ".");
} else if (i >= max) {
System.out.println("Error! Number must be less than " + max + ".");
} else {
isValid = true;
}
}
return i;
}
}
你的代碼是實在太差縮進。你已經搞糟了,如果和其他語句。正確縮進代碼並查看出了什麼問題。 – Sneh