乘法教程Java程序

时间:2015-11-29 20:11:35

标签: java loops for-loop nested-loops multiplication

我正在编写遵循这些说明的程序:

  

你的小妹妹要求你帮助她进行繁殖,你决定编写一个测试她技能的Java程序。该程序将让她输入一个起始编号,例如5.它将产生十个乘法问题,范围从5×1到5×10。对于每个问题,她将被提示输入正确答案。该程序应检查她的答案,不应让她前进到下一个问题,直到对当前问题给出正确的答案。

     

在测试了十个乘法问题后,您的程序应该询问她是否想尝试另一个起始号码。如果是,您的程序应该生成另外十个相应的乘法问题。此程序应重复,直到她指示否。

我有正确的代码要求乘法部分,但我无法弄清楚如何让程序询问用户是否想要继续。

以下代码让程序运行一次:

    package hw5;
    import java.util.Scanner;
    public class HW5 {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            System.out.print("Enter number you would like to attempt: ");
            int start = input.nextInt();
            int mult;
            for (mult = 1; mult <= 10; mult++) {
                int num = start * mult;
                System.out.print(start + " x " + mult + " = ");
                int ans = input.nextInt();
                while (ans != num) {
                    System.out.print("Wrong answer, try again: ");
                    int ans2 = input.nextInt();
                    if (ans2 == num) {
                        break;
                    } 
                }

                //System.out.print("Would you like to do another problem? ");   

            }
        }
    }

当我取消注释第21行时,程序返回:

  

输入您想要尝试的号码:1

     

1 x 1 = 1

     

你想再做一个问题吗? 1 x 2 = 2

     

你想再做一个问题吗? 1 x 3 =

     

等...

如果我从第21行获取代码并将其放在for循环之外,程序将运行for循环一次,然后直接跳转到问题。

如何解决此问题并成功完成说明?

1 个答案:

答案 0 :(得分:1)

我是这样做的:

    package hw5;
    import java.util.Scanner;
    public class HW5 {
    public static void main(String[] args) 
    {
        boolean wantsToContinue = true;
        while(wantsToContinue)
        {
            wantsToContinue = mathProblem();
        }
    }

    public static boolean mathProblem()
    {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter number you would like to attempt: ");
        int start = input.nextInt();
        int mult;
        for (mult = 1; mult <= 10; mult++) {
            int num = start * mult;
            System.out.print(start + " x " + mult + " = ");
            int ans = input.nextInt();
            while (ans != num) {
                System.out.print("Wrong answer, try again: ");
                int ans2 = input.nextInt();
                if (ans2 == num) {
                    break;
                } 
            }

            //System.out.print("Would you like to do another problem? ");   

        }

        boolean wantsToContinue;
        //Ask if the user would like to do another problem here, set "wantsToContinue" accordingly
        return wantsToContinue;
    }
}