Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialOshedhe Munasinghe
8,108 PointsNeed help in JAVA pattern FOR loop
Hello my mission is to write a program which reads a number of rows and columns entered by the user:
Answer should look like: I guess that is 3x3?
.*.*.*
*.*.*.
.*.*.*
I wrote like this
int row = 1;
int col = 1;
for (int n = 1; n <= row; n++) {
System.out.println(".*.*.*");
for (int j = 1; j < col; j++) {
System.out.println("*.*.*.");
}
The thing is 1x1 is showing perfect, but if I enter 3x3 it doesn't show correctly!!
1 Answer
Eric Queen
13,214 PointsI don't think you can accomplish this without concatenating a String variable type. Otherwise you'll never get the correct "rows". If this is what you are trying to accomplish, it would look something like this:
int row = 1;
int col = 1;
String rowString = "";
for (int n = 0; n < row; n++) {
for (int j = 0; j < col; j++) {
rowString += ".*";
}
System.out.println(rowString);
rowString = "";
}
Because of the changes you would need to set your loops' counter variables to 0. The first loop runs for each row and then runs an internal (secondary) loop immediately for each column specified. It adds the ".*" for each column to the rowString variable. After completing the internal loop for the columns it prints to the console that row with the rowString variable. Finally, before starting on the next row we need to reset the rowString variable. Otherwise it would just keep getting longer and longer for each row depending the amount of columns. Like this for a 3x3 set:
.*.*.*
.*.*.*.*.*.*
.*.*.*.*.*.*.*.*.*
Hope this helps!
Emmanuel C
10,636 PointsEmmanuel C
10,636 PointsYour answer states that, that pattern should be a 3x3. So one "Cell" should contain a
*. or .*
But your code prints
.*.*.*
as one cell so the first row of a 3x3 would look like
.*.*.*.*.*.*.*.*.*
Which one are you trying to accomplish?