开发者社区> 问答> 正文

在JAVA中为所有小于或等于N的数字计算乘法表的程序

如何编写一个程序,计算小于或等于N的所有数字的乘法表。请注意,N是从用户读取的整数。

该程序将反复做,直到用户输入-1的JAVA。

我不知道是否应该为此使用嵌套循环或方法,但是我编写了以下未完成的代码,这给了我无限循环

public static void main(String[] args) {
    int N ;
    System.out.println("Enter N: " );
    N = in.nextInt();

    while ( N != -1) {
        for(int i = 1; i <= N; ++i)
        {
            for (int c = 1; c <= 10; ++c)  
                System.out.println(N + "*" + c + " = " + (N*c));
        }
    }
}

我想要这样的输出:

Enter an integer to print it's multiplication table, -1 to
    exit
    2
    Multiplication table of 1
    1*1 = 1, 1*2 = 2, 1*3 = 3, 1*4 = 4, 1*5 = 5, 1*6 = 6, 1*7 =
    7, 1*8 = 8, 1*9 = 9, 1*10 = 10,
    Multiplication table of 2
    2*1 = 2, 2*2 = 4, 2*3 = 6, 2*4 = 8, 2*5 = 10, 2*6 = 12, 2*7
    = 14, 2*8 = 16, 2*9 = 18, 2*10 = 20, 
    Enter an integer to print it's multiplication table, -1 to
    exit  
    -1

问题来源:Stack Overflow

展开
收起
montos 2020-03-26 22:38:45 587 0
1 条回答
写回答
取消 提交回答
  • 您的代码在无限循环中运行,因为N在外部循环中不会发生变化for。

    您可以将提示放在循环内,然后更改为do-while循环以确保至少执行一次;如果用户输入的数字小于1(由于外部for循环),则不返回。

    您还缺少对Scanner进行捕获输入的参考。

    最后,您忘了使用i而不是N在输出中使用,否则内部循环每次都会输出相同的值。

    import java.util.Scanner;                              // Import Scanner
    public static void main(String[] args) {
        int N;
        Scanner in = new Scanner(System.in);               // Missing Scanner
        do {                                               // Changed to do-while loop
            System.out.println("Enter N: " );
            N = in.nextInt();                              // Prompt user for N.
            for(int i = 1; i <= N; ++i)
            {
                for (int c = 1; c <= 10; ++c)
                    System.out.println(i + "*" + c + " = " + (i*c)); // Use i instead of N
            }
        } while ( N != -1);
    }
    

    回答来源:Stack Overflow

    2020-03-26 22:39:39
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载