嵌套循环递减数
Nested loop decrement number
创建一个class,要求用户输入一个数字,然后根据int输入打印出以下模式。
所以我编写的代码结果如下所示...
12345
1234
123
12
但它应该是这样的
5
45
345
2345
12345
Scanner tri = new Scanner(System.in);
System.out.println("Enter a postive integer.");
int shape = tri.nextInt();
for(int c = shape; c > 1; --c){
for (int a = 1; a <= shape-c; a++){
System.out.print(" ");
}
for(int d = 1; d <= c; d++){
System.out.print(d);
}
System.out.println(" ");
你能试试下面这段代码吗?
Scanner tri = new Scanner(System.in);
System.out.println("Enter a postive integer.");
int shape = tri.nextInt();
for (int c = shape; c >= 1; --c) {
for (int a = 1; a <= c; a++) {
System.out.print(" ");
}
for (int d = c; d <= shape; d++) {
System.out.print(d);
}
System.out.println(" ");
}
// result
// 5
// 45
// 345
// 2345
// 12345
您可以使用一些填充来代替嵌套循环。基本上你需要一个只包含空格的字符串,并且与你的号码中的位数一样长。
在一个循环中,取你的号码的子串并用空格填充剩余部分。
我的代码:
public static void pattern(int number)
{
String s=Integer.toString(number);
String padding="";
for(int i=0;i<s.length();i++,padding+=" ");
for(int i=1;i<=s.length();i++)
{
System.out.println(padding.substring(i)+s.substring(s.length()-i));
}
}
创建一个class,要求用户输入一个数字,然后根据int输入打印出以下模式。
所以我编写的代码结果如下所示...
12345
1234
123
12
但它应该是这样的
5
45
345
2345
12345
Scanner tri = new Scanner(System.in);
System.out.println("Enter a postive integer.");
int shape = tri.nextInt();
for(int c = shape; c > 1; --c){
for (int a = 1; a <= shape-c; a++){
System.out.print(" ");
}
for(int d = 1; d <= c; d++){
System.out.print(d);
}
System.out.println(" ");
你能试试下面这段代码吗?
Scanner tri = new Scanner(System.in);
System.out.println("Enter a postive integer.");
int shape = tri.nextInt();
for (int c = shape; c >= 1; --c) {
for (int a = 1; a <= c; a++) {
System.out.print(" ");
}
for (int d = c; d <= shape; d++) {
System.out.print(d);
}
System.out.println(" ");
}
// result
// 5
// 45
// 345
// 2345
// 12345
您可以使用一些填充来代替嵌套循环。基本上你需要一个只包含空格的字符串,并且与你的号码中的位数一样长。
在一个循环中,取你的号码的子串并用空格填充剩余部分。 我的代码:
public static void pattern(int number)
{
String s=Integer.toString(number);
String padding="";
for(int i=0;i<s.length();i++,padding+=" ");
for(int i=1;i<=s.length();i++)
{
System.out.println(padding.substring(i)+s.substring(s.length()-i));
}
}