gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:28:23 24 4
gpt4 key购买 nike

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

程序会重复执行此操作,直到用户在 JAVA 中输入 -1

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

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

最佳答案

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();
}
}
}

关于java - JAVA中计算所有小于或等于N的数字的乘法表的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60673713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com