作为我们课程作业的一部分,我自己和班上的另一个人必须制作一个猜谜游戏,其中会生成一个介于 1 到 100 之间的随机数,并且用户最多有 6 次猜测来尝试猜测这个数字。我还必须创建一个“会话”,用户可以在其中输入他们的姓名,并将他们的结果存储到一个文本文件中。我已经让它工作到他们可以玩游戏并成功输入他们的名字的地步,但是如果您选择要再次玩的选项,它会显示“处理完成”并退出程序。非常感谢您的帮助,这是我到目前为止所拥有的;
代码:
import java.util.Random; //importing the Random class
import java.util.Scanner; //importing the Scanner class
/* Author Laura Brown 28/02/2014 */
public class TheGuessingGame
{
public static void main(String[] args)
{
Random generator = new Random(); //creates a random number between 1-100
int TARGET = generator.nextInt(100) + 1; //establishes the target number
int guess;
int count = 0;
String userName;
String another = "y";
Boolean flag = false;
Boolean anotherFlag = true;
Scanner consoleIn = new Scanner(System.in); //creating a new Scanner object
Scanner name = new Scanner(System.in); //creating a new Scanner object
System.out.print("Hello! Please enter your name:\n"); //asking for user input
userName = name.nextLine();
System.out.print("Hello "+ userName+ ", and welcome to the game!\n");
System.out.print("Can you guess what it is?\n");
do { //beginning the loop
guess = consoleIn.nextInt();
count++;
if (guess > TARGET)
System.out.print("Sorry - Your guess is too high \n");
else
if (guess < TARGET)
System.out.print("Sorry - Your guess is too low \n");
}
while(guess != TARGET && count < 6);
if(guess == TARGET) {
System.out.println("Congratulations! - You found it!");
System.out.println();
}
else {
System.out.println("Sorry - You have used all 6 guesses");
}
System.out.println();
System.out.println("Would you like to guess again? (yes/no)");
another = consoleIn.next();
}
}