2 回答

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
該問題的正確實(shí)現(xiàn)如下:
//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 循環(huán),記住do-while循環(huán)只需要該部分末尾的一個(gè)條件do。
你的邏輯方向是正確的,得到用戶的問題,得到答案,然后問他們是否想問另一個(gè)問題。
另外,將 交換.next()為 a.nextLine()以讓用戶決定繼續(xù)。
我剛剛在底部做了另一個(gè)小更新,以避免您添加的令人困惑的條件,因此yes = 1and no = 0。

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
您有兩個(gè)嵌套的 while 循環(huán)。你只需要一個(gè)。
使用 nextLine() -這是你的主要錯(cuò)誤。
我還將你的 int 轉(zhuǎn)換為布爾值
這是代碼:
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();
}
}
添加回答
舉報(bào)