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條經驗 獲得超8個贊
您有兩個嵌套的 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();
}
}
添加回答
舉報