2 回答
TA贡献1862条经验 获得超6个赞
该问题的正确实现如下:
//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 中的嵌套 while 循环,记住do-while循环只需要该部分末尾的一个条件do。
你的逻辑方向是正确的,得到用户的问题,得到答案,然后问他们是否想问另一个问题。
另外,将 交换.next()为 a.nextLine()以让用户决定继续。
我刚刚在底部做了另一个小更新,以避免您添加的令人困惑的条件,因此yes = 1and no = 0。
TA贡献1827条经验 获得超7个赞
您有两个嵌套的 while 循环。你只需要一个。
使用 nextLine() -这是你的主要错误。
我还将你的 int 转换为布尔值
这是代码:
package eu.webfarmr;
import java.util.Random;
import java.util.Scanner;
public class Question {
public static void main(String[] args) {
// initializing variables
boolean continueAsking = true;
String otherQ;
// 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
do{
System.out.print("What is your question? ");
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();
continueAsking = !otherQ.equalsIgnoreCase("no");
} while (continueAsking);
scan.close();
}
}
添加回答
举报