Java 使用嵌套for循环从用户输入打印给定的数字模式
我是编程新手。我现在正在学习Java,在嵌套循环中,并且被卡住了 所以我想做的是编写一个程序,从用户和 打印行,例如,如果用户输入为4,则结果应如下所示:Java 使用嵌套for循环从用户输入打印给定的数字模式,java,for-loop,nested-loops,Java,For Loop,Nested Loops,我是编程新手。我现在正在学习Java,在嵌套循环中,并且被卡住了 所以我想做的是编写一个程序,从用户和 打印行,例如,如果用户输入为4,则结果应如下所示: 1 1 2 1 2 3 1 2 3 4 以下是我目前的代码: import java.util.Scanner; public class Hello { public static void main(String[] args) { Scanner input = new Scanner(System.i
1
1 2
1 2 3
1 2 3 4
以下是我目前的代码:
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows:");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
System.out.println(i);
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
}
}
}
我很难弄明白为什么
我想这是我的第一个for循环,但我不知道如何修复for循环以获得我想要的结果
任何帮助都将不胜感激。谢谢 不要打印外循环中的任何内容,只打印新行
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
问题是同时打印换行符和
i
。。。只需处理for
循环后的新行即可。内环可以处理所有打印
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows:");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
import java.util.Scanner;
公开课考试{
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
System.out.println(“输入行数:”);
int number=input.nextInt();
对于(int i=1;i,为了避免其他答案的尾随空格,
不要在循环开始时打印i
,而是打印1
。
然后从2
开始内部循环,在每个值前打印一个空格,并在内部循环后打印一行新行
for (int i = 1; i <= number; i++) {
System.out.print("1");
for (int j = 2; j <= i; j++) {
System.out.print(" " + j);
}
System.out.println();
}
for(inti=1;i)你是什么意思,在end@Stultuske刚刚在帖子中添加,感谢您指出:)删除System.out.println(i);
并在嵌套for循环后添加System.out.println();
。
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows:");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
for (int i = 1; i <= number; i++) {
System.out.print("1");
for (int j = 2; j <= i; j++) {
System.out.print(" " + j);
}
System.out.println();
}
Let's us dry run it
at first you print
1
then newline
then j goes from 1 to 1 nut no newline now 2 is printed by i now newline
so result 1 2
again j goes like 1 , 2 but no newline so again 3 is printed by i then newline
so result 1 2 3
again j goes like 1 , 2, 3, but no newline so again 4 is printed by i then newline
so result 1 2 3 4
again j goes like 1 , 2, 3, 4 // this one is the extra line