在给出正确的输出之前,Java循环3次

我正在制作一个应用程序来测试你的政治或天文学.

我的问题是,当你说“政治”或你说“天文学”时,在给出所需的“测试”输出之前,它会再次要求你2次输入.

这是代码:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        do {
            if (getAnswer().equalsIgnoreCase("neither")) {
                System.out.println("Please enter \'astronomy\' or \'politics\'.");
            }
        getAnswer();
        }
        while(getAnswer().equalsIgnoreCase("neither"));
    System.out.println("test");
    }
    public static String getAnswer() {
        Scanner quizType = new Scanner(System.in);
        System.out.println("Would you like to be quizzed on politics or astronomy?");
        String typeAnswer = quizType.next();
        if (typeAnswer.equalsIgnoreCase("politics")) {
            return "politics";
        }
        else if (typeAnswer.equalsIgnoreCase("astronomy")) {
            return "astronomy";
        }
        else {
            return "neither";
        }
    }
}

有任何想法吗?
谢谢

最佳答案
没有必要getAnswer()3次,只需将getAnswer()放入一个String变量中就可以了.

像这样:

public static void main(String[] args) {
        String answer = "";
        do {
            answer = getAnswer();
            if (answer.equalsIgnoreCase("neither")) {
                System.out.println("Please enter \'astronomy\' or \'politics\'.");
            }
        } while (answer.equalsIgnoreCase("neither"));
        System.out.println("test");
    }

    public static String getAnswer() {
        Scanner quizType = new Scanner(System.in);
        System.out.println("Would you like to be quizzed on politics or astronomy?");
        String typeAnswer = quizType.next();
        if (typeAnswer.equalsIgnoreCase("politics")) {
            return "politics";
        } else if (typeAnswer.equalsIgnoreCase("astronomy")) {
            return "astronomy";
        } else {
            return "neither";
        }
    }

转载注明原文:在给出正确的输出之前,Java循环3次 - 代码日志