Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
非常基本的Java嵌套for循环问题_Java_Loops_For Loop - Fatal编程技术网

非常基本的Java嵌套for循环问题

非常基本的Java嵌套for循环问题,java,loops,for-loop,Java,Loops,For Loop,我很难让这段代码从5个空格开始,减少到0个空格,每行减去一个空格 public class Prob3 { public static void main(String[]args) { for (int x=1; x<=5; x++) { for (int y=5; y>=1; y--) { System.out.print(" "); }

我很难让这段代码从5个空格开始,减少到0个空格,每行减去一个空格

public class Prob3 {

    public static void main(String[]args) {

        for (int x=1; x<=5; x++)
        {
            for (int y=5; y>=1; y--)
            {
            System.out.print(" ");
            }
        System.out.println(x);
        }
    }
}
我对目前的进展感到满意,但我需要更进一步:

        1
      2
    3
  4
5

我觉得我已经很接近了

将您的内部循环更改为:

for (int y=5; y > x; y--) 
您会注意到每一行的空格数有一种模式:

  • 第1行=4个空格
  • 第2行=3个空格
  • 第3行=2个空格
  • 以此类推

因此,模式是,空白的数量是
5-rowNumber
。在代码中,外循环表示
行数
。并且内部循环应该运行
5行数
次。这就是为什么条件应该是
y>rowNumber
,即
y>x

将内部循环更改为:

for (int y=5; y>x; y--)
完整代码:

for (int x=1; x<=5; x++)
{
     for (int y=5; y>x; y--)
           System.out.print(" ");

     System.out.println(x);
}
for(int x=1;xx;y--)
系统输出打印(“”);
系统输出println(x);
}

内部for循环表达式应为:

public class Prob3 {
    public static void main(String[]args) {
        for (int x = 0; x < 5; x++) {
            for (int y = (4 - x); y > 0; y--) {
                 System.out.print(" ");
            }
            System.out.println(x + 1);
        }
    }
}
公共类问题3{
公共静态void main(字符串[]args){
对于(int x=0;x<5;x++){
对于(int y=(4-x);y>0;y--){
系统输出打印(“”);
}
系统输出打印项次(x+1);
}
}
}

问题是你每次都是5点出发。内部循环中的(4-x)是这样的,最后一个数字(5)有0个前导空格。

@Zeb homeworks在这一点上非常受欢迎,因为OP自己也尝试过,并且已经在这个问题上展示了他/她的尝试。别担心!我花了几个小时才弄到。哇!编辑:感谢大家的快速回复,第一次使用S.O.Yes,但是给出一个没有解释的答案从长远来看对他没有帮助。如果是,则应标记它。@Zeb<代码>作业标记在SO上不推荐使用。我认为有些答案太明显了,不能再加上任何解释。如果他想不出来,那就应该解释一下。实际上,内循环条件应该是“y>x”。@cacho Yeah修复了它。谢谢:)哦,好的!现在我看到了+1.
public class Prob3 {
    public static void main(String[]args) {
        for (int x = 0; x < 5; x++) {
            for (int y = (4 - x); y > 0; y--) {
                 System.out.print(" ");
            }
            System.out.println(x + 1);
        }
    }
}