If this is a homework or a lab exercise for your computer science subject read on and get the solution!
The method for printing a solid square using "*" is I guess easier than printing an inverted triangle that I already showed you how to do. :) Again here we have two classes one containing the method to print the shape and another with the main method. You can do this exercise with just one class but I’m used to making two classes having one test the other. So in my “Square” class I have a private variable “width” which is the desired width you want your square to be. I also added a constructor to set the value of “width” and finally the method “toString” to print the square. Again, I used “for” loops because it makes the solution a whole lot easier. J Here it goes:
// the class starts here!
public class Square {
private int width;
//the constructor
public Square (int _width)
{
width = _width;
}
//the method to print the square with a width of “width”
public String toString(){
String r = "";
for(int i=1; i<=width ; i++){
for(int j=1; j<=width; j++) {
r = r+ "*";
}
r = r + "\n";
}
return r;
}
}
So that's that.. :D We then make another class to test "Square". We will make another class "TestSquare" with the main method (using 10 as width, you can change this value if you want)
public class TestSquare {
public static void main(String[] args) {
Square a = new Square (10);
System.out.print(a.toString());
}
}
if you have any questions, please do leave a comment!
NOTE: This is a program that I made myself. I have tested it and came out with the desired output. I am also new in Java programming and I may not have applied the "elegant way" of writing Java programs. So please do understand. :D
This is nothing because, education is implemented in schools also demand to maximize the skills...
Do you have children before the wants of his reputation as a class, the teacher know or do they...
“Find me a tutor” is a commonly heard phrase. Nevertheless, people who know what kind of pe...
Now that everyone is asking others about ‘find me a tutor’ as looking for a private tutor f...
Basic rules in child-rearingChild's behavior, whether accepted or rejected enhanced rewards he ...
Are you ready for summer? Play up your swim wear with colorful accessories this summer. Make yo...
Craving for the perfect Charm Bracelet but can't find it in the stores or online? We have the s...
So you've downloaded the .abr file, what's next? Read this tutorial and learn the how-to!...
Ever wondered how those pros did it? Learn it here! Turn your photos into amazing vectors as a ...
Asia has different recipes for fried plantains, and I'm sharing mine! Real easy and delicious!...