所以我正在尝试练习Java。我是初学者。 我有这个练习,要求我编写一个嵌套的 for 循环。
结果应该是这样的:
Enter the size:4
Triangle is:
1
22
333
4444
Enter the size:6
Triangle is:
1
22
333
4444
55555
666666
这是我的代码:
public static void main(String arg[]){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the size:");
int size=scanner.nextInt();
System.out.println("Triangle is:");
//add your nested for loop logic here
//start
for(int i = 1; i <= size; i++)
{
System.out.println(i);
for(int j = 1; j < size; j++)
{
}
我正在尝试解决这个问题,但我似乎想不出其他方法。 那么我需要做什么?
最佳答案
使用以下循环:
for (int i = 1; i <= size; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.println();
}
这将产生:
Enter the size:
4
Triangle is:
1
22
333
4444
内循环将打印数字 i
, i
时间作为变量j
从 1
开始运行至i
。然后在下一行中我们引入一个新行。
关于java - 我对这个嵌套 for 循环没有想法了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32599499/