Magic 8 Ball程序如何正确使用Java中的方法

How to properly use methods in Java for Magic 8 Ball program

我没有要粘贴的代码,因为我只有一个要使用的方法模板。希望这不会太宽泛,因为我已经查看了所有内容,但没有收到我需要的答案。

很多人都看过或听说过 "Magic 8 Ball" 节目。用户提出问题,他们在 return 中收到随机答案。我本来可以用一种方法轻松编写代码,但现在我们已经深入研究使用多种方法,我遗漏了一块拼图。

本期节目规则: 1) 我必须至少创建三种方法:主要方法、输入方法和输出方法。 2) 我必须对随机答案使用 switch 语句。 3) 我必须使用 while 循环(或 do-while)来提示用户要么问另一个问题,要么退出。

我认为我唯一的问题在于将每段代码放在哪里。我需要打电话给扫描仪。这没什么大不了的。我知道如何执行 switch 语句。我知道如何随机化输出。我很可能会为 keep going/quit 部分使用布尔值。但是我实际上应该把扫描仪放在哪里呢?布尔值?在主要?在输入法中?随机化的处理部分呢?我的所有变量是否都在 main 中声明,以便它们遍布各处?

我希望我的问题有道理。

在 main 中或在构造函数中作为 class 级别对象创建一次 Scanner 比每次调用输入法时都创建要便宜得多。如果在class级创建可以直接在输入法中使用,否则如果在main方法中创建可以作为参数传递给输入法。

布尔值可以在输入法中,因为您直接比较输入并且没有更多用处。

当你有一个对象,尤其是一个昂贵的对象时,最好只在适用的情况下创建一次,或者尽可能少地创建它。

请原谅我草率的代码,请忽略案例名称。它们是临时的,因为我将重命名它们。编译后我尝试了每个场景。我问了一个问题,它回答了,然后问我是否想问另一个问题。我问了另一个,它重复了提示。我回答了"n",它说"Thanks for playing. Goodbye",然后停止了运行。这是我的代码。问题已解决。

    import java.util.Scanner;

public class 魔术球 {

public static void main(String[] args) {

    int random = 0;
    boolean playAgain = true;

   while (playAgain) {
       askAnother(random);
    }//end while
}//end main


public static void askAnother(int r) {

    System.out.print("Hello! What is your question? ");
    Scanner input = new Scanner(System.in);
    String question = input.nextLine();

    String yes_or_no;
    String next_question;
    randomAnswer(r);

    boolean playAgain = true;

    while(playAgain) {
        System.out.println("Would you like to ask another question? Y to ask, N to quit.");

        yes_or_no = input.nextLine();

        if (yes_or_no.equalsIgnoreCase("Y")) {
            System.out.println("What is your next question?");
            next_question = input.nextLine();
            randomAnswer(r);

        }//end if

        else if (yes_or_no.equalsIgnoreCase("N")) {
        playAgain = false;
        System.out.println("Thanks for playing. Goodbye.");
        System.exit(0);
    }
        else {
            System.out.println("Invalid Input. Please enter Y or N.");
            continue;
        }//end else
    }//end while
}//end input method

public static int randomAnswer(int r1) {

    r1 = (int)(Math.random() * 9);

switch(r1) {
    case 0: System.out.println("Yes"); break;
    case 1: System.out.println("Yes1"); break;
    case 2: System.out.println("Yes2"); break;
    case 3: System.out.println("Neutral"); break;
    case 4: System.out.println("Neutral1"); break;
    case 5: System.out.println("Neutral2"); break;
    case 6: System.out.println("No"); break;
    case 7: System.out.println("No1"); break;
    case 8: System.out.println("No2"); break;

}//end switch
return r1;

}//结束输出方法

}//结束魔法球class