请求回答,直到给出正确答案? Java Eclipse

时间:2013-08-17 19:21:31

标签: java eclipse loops methods

我基本上正在使用eclipse来保留我在Java类介绍中学到的东西。我即将参加高级编程,我有一个初学者的问题......

我在下面创建了这个小程序,因为我很难理解方法。现在我有了一般概念,我有一个新问题。我在下面有一个while语句,如果您输入简单的添加问题的正确答案,它就有效。如果您输入了错误的答案,它会要求您再次尝试该问题(正如我所希望的那样)。如果再次输入错误的答案,程序将停止。我希望它提示用户输入答案,直到它们正确为止。我该怎么做呢?

import java.util.Scanner; //needed for input

public class PracticeMethod {
    public static void main(String[] args) {
        // Create a Scanner

        System.out.println(");
        System.out.println();
        makesPerfect();
        String anotherRun = "yes";

        Scanner input = new Scanner(System.in);

    }

    static void makesPerfect() {
        Scanner input = new Scanner(System.in);
        String anotherRun;
        do {

            System.out.print(" Math");
            int x = (int) (Math.random() * 10) + 1;
            int y = (int) (Math.random() * 10) + 1;

            System.out.print(" What is " + x + "+" + y + "? ");
            double answer = 0.0;
            answer = input.nextDouble();
            if (answer == x + y) {
                System.out.println(" Yes, you are correct.");

            }
            if (answer != x + y) {
                System.out.print(" No, that is not correct. ");
                System.out.println();
                System.out.print(" Why dont you try again? ");
                System.out.println();
                System.out.println();
                System.out.print(" What is " + x + "+" + y + "? ");
                answer = input.nextDouble();
            }
            System.out.println();

            System.out.print("Enter yes if you want to run again: ");
            anotherRun = input.next();
            input.nextLine(); // causes skipping issue to fix
            System.out.print("\n\n\n");
        } while (anotherRun.equalsIgnoreCase("yes"));
    }
}

1 个答案:

答案 0 :(得分:3)

if语句检查答案是否正确while循环。这样你就可以继续询问正确的答案,直到你得到它为止。

while(answer != x + y) {
    System.out.print(" No, that is not correct. ");
    System.out.println();
    System.out.print(" Why dont you try again? ");
    System.out.println();
    System.out.println();
    System.out.print(" What is " + x + "+" + y + "? ");
    answer = input.nextDouble();
}

也赞赏正确使用StackOverflow,并努力学习!也许有一天你会回答我的问题。