如何显示数字
How to display the numbers
我是 Java 编码的新手,我在编写这个程序时遇到了问题。
用户输入一个从 0 到 9 的整数,然后显示一个金字塔。例如:
用户输入:5
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
这就是我到目前为止的全部(我真的很难过)
import static java.lang.System.*;
import java.util.Scanner'
import java.util.*;
public class pyramid
{
public pyramid()
{
Scanner scan = new Scanner(System.in);
System.out.println("enter a number between 1 and 20");
int num = scan.nextInt();
for (int i = 0; i < num + 1; i++)
{
for (int j = 0; j < num - 1; j++)
{
System.out.println(" ");
}
}
}
}
欢迎并感谢任何帮助。谢谢!
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
pyramid();
}
public static void pyramid() {
Scanner scan = new Scanner(System.in);
System.out.println("enter a number between 1 and 20");
int num = scan.nextInt();
for (int i = 0; i < num + 1; i++) {
for (int j = 0; j < num - i; j++) {
System.out.print(" ");
}
for (int j = i; j > 0; --j) {
System.out.printf("%d ", j);
}
for (int j = 2; j <= i; ++j) {
System.out.printf("%d ", j);
}
System.out.println();
}
}
}
开始将您所知道的制成表格,以找到规律。假设你身高 3:
······_1
···_2 _1 _2
_3 _2 _1 _2 _3
其中 ·
是用于对齐目的的 space,_
是为第二位保留的 space。
Row 0 1 2
Spaces in front 6 3 0 (3 * (num - i - 1))
所以你想循环 j
来打印 space 的数量,然后进行另一个循环(不是在 j
内部,而是在它之后)打印降序数字到1
,然后另一个循环将升序数字打印回 i+1
。使用 System.out.printf
和格式 %2d
将在单个数字上打印 _
space。
我是 Java 编码的新手,我在编写这个程序时遇到了问题。
用户输入一个从 0 到 9 的整数,然后显示一个金字塔。例如:
用户输入:5
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
这就是我到目前为止的全部(我真的很难过)
import static java.lang.System.*;
import java.util.Scanner'
import java.util.*;
public class pyramid
{
public pyramid()
{
Scanner scan = new Scanner(System.in);
System.out.println("enter a number between 1 and 20");
int num = scan.nextInt();
for (int i = 0; i < num + 1; i++)
{
for (int j = 0; j < num - 1; j++)
{
System.out.println(" ");
}
}
}
}
欢迎并感谢任何帮助。谢谢!
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
pyramid();
}
public static void pyramid() {
Scanner scan = new Scanner(System.in);
System.out.println("enter a number between 1 and 20");
int num = scan.nextInt();
for (int i = 0; i < num + 1; i++) {
for (int j = 0; j < num - i; j++) {
System.out.print(" ");
}
for (int j = i; j > 0; --j) {
System.out.printf("%d ", j);
}
for (int j = 2; j <= i; ++j) {
System.out.printf("%d ", j);
}
System.out.println();
}
}
}
开始将您所知道的制成表格,以找到规律。假设你身高 3:
······_1
···_2 _1 _2
_3 _2 _1 _2 _3
其中 ·
是用于对齐目的的 space,_
是为第二位保留的 space。
Row 0 1 2
Spaces in front 6 3 0 (3 * (num - i - 1))
所以你想循环 j
来打印 space 的数量,然后进行另一个循环(不是在 j
内部,而是在它之后)打印降序数字到1
,然后另一个循环将升序数字打印回 i+1
。使用 System.out.printf
和格式 %2d
将在单个数字上打印 _
space。