import java.util.*;
public class GuessNumberGame
{
public static void main(String[] args)
{
System.out.println("Welcome to the Guess the Number Game" + "\n" +
"++++++++++++++++++++++++++++++++++++");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
// get the input from the user
System.out.println("I'm thinking of a number from 1 to 100"
+ "\n" + "Try to guess it." + "\n");
int randomNumber = (int)(Math.random() * 99 + 1);
int numberOfGuesses = 0;
// print out the random Number to check the game
// hide this code before turning homework
System.out.println("The answer from the system is: " + randomNumber);
// format the result as a single string
while (true)
{
int guess = getIntWithinRange(sc,"Please input valid number." + "\n",1,100);
numberOfGuesses++;
if (guess == randomNumber) // use "==" not "="
{
if (numberOfGuesses <=3)
System.out.println("You got it in " + numberOfGuesses + " tries."
+ "\n" + "Great work You are a mathematical wizard." + "\n");
else if ((numberOfGuesses > 3) && (numberOfGuesses <= 7))
System.out.println("You got it in " + numberOfGuesses + " tries."
+ "\n" + "Not too bad! You've got some potential."+ "\n");
else if (numberOfGuesses >7)
System.out.println("You got it in " + numberOfGuesses + " tries."
+ "\n" + "What took you so long? Maybe you should " +
"take some lessons."+ "\n");
break;
}
else
{
if (guess >= (randomNumber + 10))
System.out.println("Way too high! Please guess again." + "\n");
else if (guess > randomNumber)
System.out.println("Too high! Please guess again." + "\n");
else if (guess < randomNumber)
System.out.println("Too low! Please guess again." + "\n");
}
}
// see if the user wants to continue
while (true)
{
System.out.print("Try again? (y/n)");
choice = sc.next();
System.out.println();
if (choice.equals("y") || choice.equals("n"))
{
if (choice.equals("y"))
System.out.println("The new game starts." + "\n");
else if (choice.equals("n"))
System.out.println("Bye - Come back soon!");
break;
}
else if ((!choice.equalsIgnoreCase("y")) && (!choice.equalsIgnoreCase("n")))
{
if (choice.equals(""))
{
System.out.println("Error! This entry is required. Try again");
}
else
{
System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
}
}
}
}
}
public static int getIntWithinRange(Scanner sc, String prompt,int min, int max)
{
int i;
while(true)
{
System.out.print("Enter Nubmer:");
i = sc.nextInt();
if(i<min || i>max)
{
System.out.println(prompt);
}
else
break;
}
return i;
}
}
接下來的作業越來越難了,原本每週交一次的作業,老師說從下週開始改成每兩個禮拜交一次作業,希望讓我們有充足的時間寫。雖然寫作業的時間變多,但是我並沒有比較開心,因為課程越難,作業越難寫,要花在作業上的時間也更多,@@。
ReplyDelete