首页 > 解决方案 > 在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

标签: javaloopsfor-loopmethodswhile-loop

解决方案


Sunny Patel 的回答是正确的,但只是为了向您展示另一种方法:

import java.util.Scanner;
import java.util.stream.IntStream;

public class Multiply {
    public static void main(String [] args) {
        try (Scanner in = new Scanner(System.in)) {
            int N;
            do {
                System.out.println("Enter N: " );
                N = in.nextInt();
                IntStream.range(1, N+1)
                     .forEach(i -> IntStream.range(1, 11)
                                            .forEach(j -> System.out.println(String.format("%d*%d = %d", i, j, (i*j)))));
            } while ( N != -1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

推荐阅读