简体   繁体   中英

Why are my nested loops printing an extra space at the end of the loops?

For every number I print, I want that many spaces of indent before the number. for some reason after the last number, it prints another line with the next number of spaces.

  userNum  = 3;

  for(i=0; i<=userNum; ++i) {
     System.out.println(i);
        for( j=0; j<=i; ++j) {
        System.out.print(" ");  
        }
  }  

Try changing j<=1 to j<1:

userNum  = 3;

for(i=0; i<=userNum; ++i) {
 System.out.println(i);
 for( j=0; j<i; ++j) {
  System.out.print(" ");  
 }
}  

This should only print the spaces up until j = (userNum - 1) in this case, 2.

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