简体   繁体   English

java循环的小帮助

[英]little java help with loops

Hi I am doing some practice problems and trying to print a diagonal line like the example below. 嗨,我遇到一些练习问题,并尝试打印对角线,如下例所示。 I have writen the program you see below and I honestly dont understand what I am doing wrong. 我已经编写了您在下面看到的程序,老实说我不明白我在做什么错。 I ma java beginner and I cant see how to find the error. 我是Java初学者,看不到如何查找错误。

Example: 例:

*
  *
    *
      *
        *

code: 码:

class Diagonal{
  public static void main(String args[]) {
    int row, col;


    for(row = 1; row < 6; row++) {
      for(col = 1; col <= row; col++) {
          if(col==row){
            System.out.print("*");
          } else{
              System.out.print("");
          }
          System.out.println();     
      }
    }
  }
}

I am trying to learn for loops because they really confuse me. 我正在尝试学习循环,因为它们确实使我感到困惑。 Another practice is to print a similar diagonal line but this time from right to left. 另一种做法是打印一条类似的对角线,但是这次是从右到左。 I cant do that without getting this right however :( I believe they will be pretty similar? Above my reasining is this: As long as the column # is the same as the row number the print the line or otherwise leave a blank....what's wrong with how i did it? 我不能做到这一点,但是:(我相信它们会非常相似吗?在我上面的简化是:只要列号与行号相同,就打印行,否则留空... 。我怎么做的呢?

THANK YOU! 谢谢!

You never print any space character. 您永远不会打印任何空格字符。 You print an empty String. 您打印一个空的字符串。 Replace 更换

System.out.print("");

with

System.out.print(" ");

Also, you write a newline after each column rather than writing one after each row. 同样,您在每一列之后写一个换行符,而不是在每一行之后写一个换行符。

String spaces = "";

for(int row = 1; row < 6; row++) {
    System.out.println(spaces+"*");
    spaces += " ";
}
  1. Print new lines when entering a star: System.out.println("*"); 输入星号时打印新行: System.out.println("*");
  2. Add spaces: System.out.println(" "); 添加空格: System.out.println(" ");
  3. remove the line where you print new lines between columns. 删除在列之间打印新行的行。

as said before replace black with space and move the end line to the end of the FIRST for() like this: 如前所述,将黑色替换为空格,然后将结束线移至for()的第一个FIRST的末尾,如下所示:

class Diagonal{
  public static void main(String args[]) {
    int row, col;


    for(row = 1; row < 6; row++) {
      for(col = 1; col <= row; col++) {
          if(col==row){
            System.out.print("*");
          } else{
              System.out.print(" ");
          }
      }
      System.out.println();     
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM