以下是参数:
创建一个名为get8BallAnswers的方法(2分) 该方法应该没有参数 该方法将构建可能的String答案数组(来自BA5),并返回整个数组
重载get8BallAnswers方法(2分) 该方法应该有1个整数参数,用户可以在其中传递一个随机数 该方法应从数组中返回1个可能的String答案。提示:您可以使用在步骤2中创建的方法来检索答案数组。
创建一个名为magic8Ball的方法,它基本上会运行整个程序。 (2分) 它应该要求用户输入8 Ball的问题,生成一个随机数,并将其传递给上述方法之一以获得响应。 您将在main方法中调用此magic8Ball方法。 应该在do-while循环中调用该方法,如果用户想要再次运行程序,则重复该方法。
这就是我所拥有的:
package magic8;
import java.util.Random;
import java.util.Scanner;
public class magic8Ball {
public static String[] get8BallAnswers() {
String[] ball;
return ball = new String[] {"Yes, of course!", "Without a doubt, yes.",
"You can count on it.", "For sure!", "Ask me later.", "I'm not sure.", "I can't tell you right now", "I'll tell you after my nap.", "No way!", "I don't think so.", "Without a doubt, no.", "The answer is clearly No."};
}
public static void main(String[] args) {
boolean run = true;{
while (run) {
magic8Ball();
System.out.println("Do you want to try again, yes or no?");
Scanner scnr = null;
String go = scnr.nextLine();
go = go.toLowerCase();
if (go.equals("n")) {
System.out.println("Goodbye");
run = false;
}
if (go.equals("no")) {
System.out.println("Goodbye");
run = false;}
}
}
}
public static void magic8Ball() {
Scanner input = new Scanner(System.in);
String response;
System.out.println("Please ask me a question.");
response = input.nextLine();
Random gen = new Random();
int pick = gen.nextInt(ball.length);
System.out.println(ball[pick]);
return;
}
}
我无法让随机数生成器将整数传递给数组球以获得响应。
答案 0 :(得分:0)
试试这个
private static Scanner scanner = new Scanner(System.in);
private static String[] get8BallAnswers() {
return new String[] {"Yes, of course!", "Without a doubt, yes.", "You can count on it.",
"For sure!", "Ask me later.", "I'm not sure.", "I can't tell you right now",
"I'll tell you after my nap.", "No way!", "I don't think so.",
"Without a doubt, no.", "The answer is clearly No."};
}
private static String get8BallAnswers(int num) {
return get8BallAnswers()[num];
}
public static void main(String[] args) {
while (true) {
magic8Ball();
System.out.println("Do you want to try again, yes or no?");
if (scanner.nextLine().toLowerCase().contains("n")) {
System.out.println("Goodbye");
break;
}
}
}
private static void magic8Ball() {
System.out.println("Please ask me a question.");
scanner.nextLine();
System.out.println(get8BallAnswers(new Random().nextInt(get8BallAnswers().length)));
}