File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes numbers to spaces Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "numbers to spaces" Watch "numbers to spaces" New topic
Author

numbers to spaces

charlie mills
Ranch Hand

Joined: Nov 01, 2008
Posts: 49
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
Sheriff

Joined: Sep 28, 2004
Posts: 19070
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
charlie mills
Ranch Hand

Joined: Nov 01, 2008
Posts: 49
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
Sheriff

Joined: Sep 28, 2004
Posts: 19070
    
  40

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

Joined: Oct 02, 2003
Posts: 11499
    
  16

here's a hint about the loop...

printing 3 spaces one time is the same as printing 1 space three times...


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
charlie mills
Ranch Hand

Joined: Nov 01, 2008
Posts: 49
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

Joined: Oct 13, 2005
Posts: 40052
    
  28
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: numbers to spaces