我想创建一个神奇八号球程序:
存储所有在一个String数组,使用初始化列表的响应。
生成用于使用随机对象(取值范围为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
太感谢你对我的帮助!
对于这一问题的正确实施情况如下:
//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
System.out.print("Would you like to ask another question? (Answer yes or no): ");
otherQ = scan.nextLine();
} while (otherQ.equalsIgnoreCase("yes"));
您可以删除嵌套循环的同时在做,同时,记得有一个do-while
环只需要一个条件在结束do
部分。
你的逻辑是在正确的方向,得到了用户的问题,得到的答案,然后问他们是否要问另外一个问题。
此外,交换.next()
到.nextLine()
用于获取用户决定继续。
我只是在底部形成另一个小更新,以避免您添加,使混乱的条件语句yes = 1
和no = 0
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句