patternjavaMinor
2D array to draw a letter 'F'
Viewed 0 times
arraydrawletter
Problem
This is my code to print letter 'F' with nested loop 2d array. Are there changes that could be made in it to make it look better or more efficient?
for (int i=0;i<=4;i++){
for(int j=0;j<=4;j++){
array[i][j]='*';
if ( array[1][1]=='*' || array[1][2]=='*' || array[1][3]=='*' || array[1][4]== '*'||
array[3][1]=='*' || array[3][2]=='*' || array[3][3]=='*' || array[3][4]== '*'
||array[4][1]=='*' || array[4][2]=='*' || array[4][3]=='*' || array[4][4]== '*')
{
array[i][j]=' ';
}
}
}
for (int i=0;i<=4;i++){
for(int j=0;j<=4;j++){
System.out.print(" "+array[i][j]);
}
System.out.println("\n");
}Solution
I can't imagine any good reason for drawing an F using that approach. Drawbacks include:
A solution like this, for example, is much easier to understand. It would also be more efficient, since all of the output is done in one
- It is not obvious at all, just from looking at the code, what the expected output is.
- Not only is the code hard to read, it is also hard to write and modify.
- Using many small
System.out.print()calls is very inefficient.
A solution like this, for example, is much easier to understand. It would also be more efficient, since all of the output is done in one
System.out.print() call.public static final String F =
"*****\n" +
"* \n" +
"*****\n" +
"* \n" +
"* \n";
public static void main(String[] args) {
// Print with 2x magnification
System.out.print(F.replace("*", " *").replace("\n", "\n\n"));
}Code Snippets
public static final String F =
"*****\n" +
"* \n" +
"*****\n" +
"* \n" +
"* \n";
public static void main(String[] args) {
// Print with 2x magnification
System.out.print(F.replace("*", " *").replace("\n", "\n\n"));
}Context
StackExchange Code Review Q#104405, answer score: 4
Revisions (0)
No revisions yet.