Reputation: 35
I'm trying to get a single line to output and look somewhat like this:
1 2 3 4 5 6 7 8 9
Adding another space every time the number increases. I need to do it using for loops, with a nested for loop being preferred. Here's my code so far (on run it doesn't print even with the method call.)
public static void outputNine()
{
for(int x=1; x<=9; x++)
{
for(char space= ' '; space<=9; space++)
{
System.out.print(x + space);
}
}
}
I know I'm doing something wrong, but I'm fairly new to java so I'm not quite sure what. Thanks for any help.
Upvotes: 0
Views: 7287
Reputation: 41
Please find my simple solution:)
public class Test {
public static void main(String args[]) {
for (int i = 1; i <= 9; i++) {
for (int j = 2; j <= i; j++) {
System.out.print(" ");
}
System.out.print(i);
}
}
}
Upvotes: 0
Reputation: 8587
Consider the line as composed of 9 parts of the same structure: x-1
spaces followed by x
, where x
change from 1 to 9.
/*
0 space + "1"
1 space + "2"
2 spaces + "3"
...
*/
int n = 9;
for (int x = 1; x <= n; x++) {
// Output x - 1 spaces
for (int i = 0; i < x - 1; i++) System.out.append(' ');
// Followed by x
System.out.print(x);
}
One good thing about this approach is you don't have trailing spaces.
Upvotes: 0
Reputation: 191710
You only need one loop.
Refer: Simple way to repeat a String in java
for (int i = 1; i <= 9; i++) {
System.out.printf("%d%s", i, new String(new char[i]).replace('\0', ' '));
}
Output
1 2 3 4 5 6 7 8 9
Or more optimally,
int n = 9;
char[] spaces =new char[n];
Arrays.fill(spaces, ' ');
PrintWriter out = new PrintWriter(System.out);
for (int i = 1; i <= n; i++) {
out.print(i);
out.write(spaces, 0, i);
}
out.flush();
Upvotes: 0
Reputation: 56636
You can initialize space
only once, then print the numbers, and for every number, print the spaces:
char space = ' ';
for(int x=1; x<=9; x++)
{
System.out.print(x);
for(int i = 0 ; i < x ; i++)
{
System.out.print(space);
}
}
Upvotes: 2
Reputation: 50716
Your loop is using the ASCII value of ' '
, which isn't what you want. You just need to count up to the current x
. Replace your inner loop with this:
System.out.print(x);
for (int s = 0; s < x; s++) {
System.out.print(" ");
}
Upvotes: 0
Reputation: 81
Right now you're trying to increment a char, which doesn't make sense. You want space
to be a number equivalent to the number of spaces you need.
Upvotes: 0