Shammy Shammy - 3 months ago 9
Java Question

How to print out 10 rows of 10 characters (or strings) in java non-tediously

I'm going through a beginners exercise for writing a small program in Java. My task is to print out (i.e. find an algorithm) the following output

XOOOOOOOOO
XXOOOOOOOO
XXXOOOOOOO
XXXXOOOOOO
XXXXXOOOOO
XXXXXXOOOO
XXXXXXXOOO
XXXXXXXXOO
XXXXXXXXXO
XXXXXXXXXX


I have figured out how to do it but the code I wrote seems repetitive and tedious. How can I shorten my code? There must be an easier way to achieve this?

Here is my code as of now;

package helloWorld;

public class HelloWorld {

public static void main(String[] args)
{
// Output


// Algorithm 1

boolean ft = true;

String s = new String();
for(int i = 0; i < 10; i++)
{
s += "X";
for(int j = 0; j < 9; j++)
{
if(i == 0)
{

s += "O";
}

if(i == 1)
{

if(ft == true)
{
s+="X";
ft = false;
}
if(j == 8)
{
continue;
}
s += "O";
}

if(i == 2)
{

if(ft == true)
{
s+= "XX";
ft = false;

}

if(j == 7)
{

break;
}
s += "O";

}

if(i == 3)
{

if(ft == true)
{
s+= "XXX";
ft = false;

}

if(j == 6)
{

break;
}
s += "O";
}

if( i == 4)
{
if(ft == true)
{
s+= "XXXX";
ft = false;

}

if(j == 5)
{

break;
}
s += "O";
}

if( i == 5)
{
if(ft == true)
{
s+= "XXXXX";
ft = false;

}

if(j == 4)
{

break;
}
s += "O";
}

if( i == 6)
{
if(ft == true)
{
s+= "XXXXXX";
ft = false;

}

if(j == 3)
{

break;
}
s += "O";
}

if( i == 7)
{
if(ft == true)
{
s+= "XXXXXXX";
ft = false;

}

if(j == 2)
{

break;
}
s += "O";
}

if( i == 8)
{
if(ft == true)
{
s+= "XXXXXXXX";
ft = false;

}

if(j == 1)
{

break;
}
s += "O";
}

if( i == 9)
{
if(ft == true)
{
s+= "XXXXXXXXX";
ft = false;

}

if(j == 0)
{

break;
}
s += "O";
}


}
System.out.println(s);
s = "";
ft = true;

}
}

}

Answer

Just use 2 nested loops:

String s;
for( int i = 0; i < 10; i++)
{
    s = "";
    for( int j = 0; j <= i; j++)
        s+= "X";
    for( int j = i+1; j < 10; j++)
        s+= "O";
    System.out.println(s);
}