Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Java printing square pattern numbers --missing part  RSS feed

 
Frank Poupard
Ranch Hand
Posts: 65
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I would to print the following pattern, but somehow, I don't get the first column and the first row, which I don't really understand. Thanks for explanation !

00 10 20 30 40 50 60 70 80 90
01 11 21 31 41 51 61 71 81 91
02 12 22 32 42 52 62 72 82 92
03 13 23 33 43 53 63 73 83 93
04 14 24 34 44 54 64 74 84 94
05 15 25 35 45 55 65 75 85 95
06 16 26 36 46 56 66 76 86 96
07 17 27 37 47 57 67 77 87 97
08 18 28 38 48 58 68 78 88 98
09 19 29 39 49 59 69 79 89 99

here is the little code :


 
Knute Snortum
Sheriff
Posts: 4073
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a classic "off by one" problem. Think about when your for loop ends. From x=0 to x<9. How many is that?
 
Fred Kleinschmidt
Bartender
Posts: 560
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you try going through the code by hand and see what is happening? You start off by setting x to zero, then increment x, so x is now one. Then you enter the inner loop and add ten to x, so x is eleven when you first print it. Also, if you want 10 columns, why do you use x<9 for the inner loop termination condition?
 
Campbell Ritchie
Marshal
Posts: 55751
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't use \n. Use
System.out.println();
Don't use simple print(x). Use
System.out.printf(%02d ", i);

Or better still, append the numbers and space and System.lineSeparator() to a StringBuilder; then you only need one print call.
System.out.println(myStringBuilder);
 
Frank Poupard
Ranch Hand
Posts: 65
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks you for your answers, I'm fixing it.
 
Campbell Ritchie
Marshal
Posts: 55751
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a pleasure Do show us your solution when you find it.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!