java - 在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
解决方案
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();
}
}
}
推荐阅读
- javascript - 这两者之间有什么区别?
- ios - 使用 pullView 解决 UIKit 错误?
- ssh - 我可以将这些 SSH 隧道命令组合成一个命令吗?
- linux - espeak-ng 交叉编译使安装问题
- android - 在 vulkan 中绘制到帧缓冲区时出现 ioctl 错误
- heroku - 为什么我的 heroku flask 应用程序需要 procfile,但我的 heroku express.js 或 rails 应用程序不需要 procfile?
- python - PTable 中的箭头导航
- notifications - Slack 通知在 Windows 8 上不起作用
- python - 如何通过 Pyqt 在 Qtablewidget 中更改边框粗细
- c# - Windows 服务 C# - 数据库连接上的错误 1064,从数据库创建 XML