• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

numbers to spaces

 
charlie mills
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to create a program where the user inputs a number and, after a calculation, displays a certain number of spaces on the screen, followed by a star.
e.g. If the user enters the number 9, the calculation would work out that 4spaces are needed, followed by *.

Is there any way I can get the number 4 to convert into 4 spaces?
 
Henry Wong
author
Marshal
Pie
Posts: 21490
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What have you tried so far?

Hint: There are multiple ways to do this. Two options are to build it in a loop, or truncate it from a string of spaces with a substring.

Henry
 
charlie mills
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I havent tried anything because i dont know how to do it. I've got as far as getting the user to enter the number, and then performing the calculation, but I don't know how to get the answer to the calculation into the corresponding number of spaces.

How would i build it in a loop?
 
Henry Wong
author
Marshal
Pie
Posts: 21490
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How would i build it in a loop?



Take a shot at it. It isn't that hard. I am assuming that you have learned the looping constructs -- for, while, do-while ? Or at least, one of them?

Henry
 
fred rosenberger
lowercase baba
Bartender
Posts: 12196
35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here's a hint about the loop...

printing 3 spaces one time is the same as printing 1 space three times...
 
charlie mills
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
everything just sort of clicked and i managed to do it with a for statement. thanks

the only thing is, it prints an extra space. i've managed to fix it by takning out the equals sign, but i shouldn't have to do this should i? i cant see why its printing an extra one

for (int spaces = 0; spaces <= spacesOnFirstRow; spaces++)
{
System.out.print(" ");
}
 
Campbell Ritchie
Sheriff
Pie
Posts: 50171
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Go through the for loop very carefully, with a pencil and paper, and work out how many times it loops if you want to print, say 2 spaces.

I could tell you, but you will remember what causes this sort of error a lit better if you work it out for yourself. This is a very common sort of error, called an out-by-one error.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic