我正在尝试创建一个 Magic 8 Ball 程序:
使用初始值设定项列表将所有响应存储在字符串数组中。
使用随机对象(范围在 0 到 19 之间)生成响应的随机数。
提示用户输入问题。
使用随机数来访问并显示相应的响应。
询问用户是否想问另一个问题(使用 do-while 循环)。只要用户说“是”,代码就应该重复。
我在执行第 5 步时遇到问题。
所有其他步骤我都能够很好地完成,但是当我输入“是”时,它不会让我问另一个问题,而是会跳过该问题并给我答案。
这是我到目前为止所拥有的:
//initializing variables
int stop = 0;
String otherQ,q;
//initializing array
String[] responses = {
"It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes - definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy, try again.",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count on it.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Very doubtful."};
//creates objects
Scanner scan = new Scanner (System.in);
Random rn = new Random();
//input
//THIS IS WHERE I AM HAVING A PROBLEM.
do {
System.out.print("What is your question? ");
q = scan.nextLine();
System.out.println(responses[rn.nextInt(19)]); //method caller
while (stop == 0) {
System.out.print("Would you like to ask another question? (Answer yes or no): ");
otherQ = scan.next();
if (otherQ.equalsIgnoreCase("yes")){
break;
}else if (otherQ.equalsIgnoreCase("no")){
stop = 1;
}
}
} while (stop == 0);
我的预期结果是:
What is your question? Question goes here
As I see it, yes.
Would you like to ask another question? (Answer yes or no): yes
What is your question? Cannot predict now.
Would you like to ask another question? (Answer yes or no):
我用上面的代码得到的结果:
What is your question? Question goes here
It is certain.
Would you like to ask another question? (Answer yes or no): yes
What is your question? Question goes here
Would you like to ask another question? (Answer yes or no): no
非常感谢您对我的帮助!
阿波罗的战车
慕仙森
相关分类