You could use the escape sequence "\n" after you print out the 4th element in the array? Or use just System.out.println(); after the 4th element has been printed.
majestic0110
Nearly a Posting Virtuoso
1,328 posts since Oct 2007
Reputation Points: 256
Solved Threads: 72
The second option is better as "\n" is platform specific and is not always guaranteed to get the effect you wanted.
masijade
Industrious Poster
4,253 posts since Feb 2006
Reputation Points: 1,471
Solved Threads: 494
... "\n" is platform specific and is not always guaranteed to get the effect you wanted.
Just in case this matters: you can use
System.getProperty("line.separator");
to get the line separator string appropriate to the current platform.
JamesCherrill
Posting Genius
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
Yes. In fact thats very common, using 1d array as a mimic of a 2d.
final int ROW = 5;
final int COL = 5
char[] Letters = new char[ ROW * COL];
for(int i = 0; i < ROW * COL; i++)
Letters[i] = (char)( 'A' + i );
for(int i = 0; i < ROW; i++)
{
for(int j = 0; j < COL; j++)
{
System.out.print( Letters[j + i * ROW] + " " );
}
}
It hasn't been tested, but you should get the idea, if it doesn't work.
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
In this there is restriction that the array dimension can't be prime
Why is that again?
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
This was was not working for me.
It works for me :
import java.*;
class Main
{
static void Print(Object ob){
System.out.print(ob);
}
static void Print() {
System.out.println();
}
public static void main(String[] Arg)
{
final int ROW = 5;
final int COL = 5;
char[] fake2D = new char[ROW*COL];
for(int i = 0; i < ROW*COL; i++)
fake2D[i] = (char)('A' + i);
for(int i = 0; i < ROW; i++)
{
for(int j = 0; j < COL; j++)
{
if(i > 0 && i % ROW == 0)
Print();
Print(fake2D[j + i * ROW] + " ");
}
Print();
}
}
}
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
This is great, but how would I go about preventing duplicates when the array is randomized?
You could sort it and then check if the next element is the same and
work from there.
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608