【问题标题】:Java Nested Loop Triangle [Basic]Java 嵌套循环三角形 [基础]
【发布时间】:2014-03-06 04:45:22
【问题描述】:

所以任务是让系统输出一个三角形,其中的空格在 x 之间递增,如下所示(为了便于阅读,添加破折号代替空格):

xx
x-x
x--x
x---x
x----x
x-----x
x-----x
x-------x

所以,我以前做过这个,看起来很容易,但我遇到的问题是让初始的空格数量正确。我想要一个如何做到这一点的例子,以及为什么它尽可能简单明了地工作,谢谢。这是我到目前为止的代码以及输出:

    Scanner in = new Scanner(System.in); 
    System.out.println("How many columns");
    col = in.nextInt();
    for (int i = 0; i < col; i++)
    {
        System.out.print("#");
        for(int j = 0; j < (i+ 1); j++)
        {
            System.out.print(" ");
        }
        System.out.print("#");
        System.out.println();
    }

输出(当 cols = 4 时):
x-x
x--x
x---x
x----x

非常感谢所有帮助:)

【问题讨论】:

  • 一步一步来,看看A步会发生什么,然后再进行B步...
  • 您发布的代码似乎无法编译。你的意思是Scanner in = new Scanner(System.in);
  • 先把逻辑写在纸上。

标签: java loops nested logic


【解决方案1】:
public static void main(String[]args){
System.out.println("How many columns?");
int columns = new Scanner(System.in).nextInt();

for(int i=0; i<=columns; i++){
  String toPrint = "x";
  for(int cols=0; cols<i; cols++){
      toPrint+=" ";
  }
  System.out.println(toPrint+"x");

}

} 

【讨论】:

    【解决方案2】:

    如下改变 j 的条件。您也已将变量声明为 col 并像 cols 一样使用它。所以先改正。

    Scanner in = new Scanner; 
    System.out.println("How many columns");
    col = in.nextInt();
    for (int i = 0; i < col; i++)
    {
        System.out.print("#");
        for(int j = 0; j < i; j++)
        {
            System.out.print(" ");
        }
        System.out.print("#");
        System.out.println();
    }
    

    【讨论】:

      【解决方案3】:

      我认为问题在于最初设置的 r 值。不需要设置新的变量 r。

      如果 i 小于 j,则循环不会第一次执行,并且循环比外 for 循环的每次迭代多执行 1 步

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多