java - 嵌套循环递减数

标签 java nested-loops

创建一个类,要求用户输入数字,然后根据 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 

关于java - 嵌套循环递减数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55643577/

相关文章:

bash - 嵌套 For 循环计数器重置

java - 如何找到 ReSTLet 框架 2.1 版中使用的 Jetty 版本?

java - retrofit / Dagger - Android : Fatal Exception: API declarations must be interfaces

java - Android Studio 中 Seekbars( View )的径向布局

knockout.js - 在嵌套循环中获取祖 parent 的 $index

python - 通过匹配列表中的字符串值在 Pandas 数据框中构建新列

arrays - 检查一个数组是否包含另一个数组中的值

java - 将文档流发送到 Jersey @POST 端点

java - 无法使用 Twilio 配置 OTP

python - 带游标的嵌套 for 循环只能在 python 上获得第一个期望的结果