Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# numbers to spaces

charlie mills
Ranch Hand
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
Marshal
Posts: 21743
85
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
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
Posts: 21743
85
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: 12234
36
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
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
Posts: 50702
83
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.