• Post Reply Bookmark Topic Watch Topic
  • New Topic

Exercise i m having trouble with  RSS feed

 
Tiberius Marius
Ranch Hand
Posts: 115
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I found an exercise i m having trouble completing on my own .The exercise sounds like this :

Write a program that prompts the user to enter an integer from 1 to 15 and displays a pyramid , as shown in the following sample run (my code displays correctly the first 9 lines):


The problem is when i input a number greater then 9 as it requires 2 spaces . I m pritty sure i solved it incorrectly or at lost not optimal as i m using a string that decreases on each line to create the pyramid effect.



[edited to fix formatting]
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37465
539
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If fixed the formatting for you on the pyramid so it displays properly in the formatting. (I used the code tag with a type of "text").

On to your question. Why not just treat all numbers as two digit numbers and display a space for the first digit when is is 0-9?
 
Tiberius Marius
Ranch Hand
Posts: 115
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Managed to solve it trough i must say i hate this kind of graphical output /nested loops !

 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can improve that no end by printing a single String a certain number of times before your numbers.Because multiple print calls are slow, I would suggest you consider putting the whole thing into a StringBuilder, then you can print out the entire StringBuilder as one print call.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!