简体   繁体   中英

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.

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("*");
  2. Add spaces: 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:

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();     
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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