java猜谜游戏它不会循环
作为我们课程的一部分,我和我班上的另一个人必须做一个猜测游戏,其中随机数在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();
}
}
# 1 楼答案
您需要添加另一个循环。从风格上讲,我会避免使用do。。。while循环,因为它们很难阅读。我已经包括了一个以更传统的方式做的while循环,向你展示他们是多么的性感
如果用户输入“否”,则需要将另一个标志设置为false。这应该是一个相对简单的练习,但是上面的练习会让程序反复循环
# 2 楼答案
添加了另一个循环来循环整个游戏过程。并将随机生成方法降到循环内,以重新生成一个新的数字。试试看。不管怎样,我又加了一行。nextLine();用户输入后,清除回车缓冲区。next()方法