0
What mistake am I making in my code? Exam tomorrow!
I want to print a 4x4 square or stars, with just the outline for e.g **** * * * * **** I am getting only the 1st and 4th row in the output. The code I have right now is the following : for (int row=1;row <=4:row++){ for(int column=1;column <=4;column++){ if (row==1||row==4){ System.out.print("*");} else System.out.println ("");} }}} Im having trouble with nested for loops.
8 odpowiedzi
+ 4
I just did this fast so i just shortened the names. Please either study off this answer key or try another similar problem without help to assure you understand this concept and good luck on the exam.
edit: You can (should) do it how luca said, he/she did it a better way for this problem. (you can ignore my code)
for(int r = 1; r <= 4; r++)
for(int c = 1; c <= 4; c++){
if(r == 1 || r == 4 || c == 1 || c == 4)
System.out.print("*");
else if (c == 2 || c == 3)
System.out.print(" ");
if(c == 4)
System.out.println();
}
+ 3
*You only want to print to a new line after the 4th col.
*leave middle spots blank if its not the 1st or 4th row. You have it so that your going on a new line for all the empty spots.
You want to go from top left to top right, and work your way down from left to right.
(1) ****
(2) * *
etc..
+ 1
else{
if(column==1||column==4){
...
}
else{
...
}
}
EDIT: What Rrestoring says is true, you probably want to print all the line at the same time so it is aligned. I.E.:
for(...){
if(row==1||row==4) println("****");
else println("* *");
}
0
That's because if the row is not 1 or 4 you print blank lines, you should print something in the else part if the column is 1 or 4 and if not, print spaces.
0
could you fix the code?
0
If you could give me a link to edit it I can try and even share the code with you :) but I won't copy the code manually since I'm on my phone.
0
how do I put an if condition like you said in the else part?
0
thank you so muchh!❤