If this is a homework or a lab exercise for your computer science subject read on and get the solution!
This took me some time before I got the solution. Printing a solid square is easy, but a hollow one is a little bit tricky. For this exercise I used an “if-else” statement so I can create the hollow space in the square. So this is class “HollowSquare”. I still have the private variable “width” for the desired width of the hollow square, and also a constructor to set the “width” variable. And of course the “toString” method to create and print the hollow square.
// class starts here!
public class HollowSquare {
private int width;
//the constructor for “HollowSquare”
public HollowSquare (int _width){
width = _width;
}
// the toString method to create and print the hollow square
public String toString(){
String r = "";
for(int i=0; i
for(int j=0; j
if(i==0 || j==0 || i==(width-1))
r = r + "*";
else if (j==(width-1))
r = r + "*";
else
r = r + " ";
}
r = r + "\n";
}
return r;
}
}
So there, the hard part’s done! :D So we then make another class “TestHollowSquare” with the main method (using 10 as width, you can change this value if you want to) to test the class “HollowSquare”.
public class TestHollowSquare {
public static void main (String[] args){
HollowSquare b = new HollowSquare (10);
System.out.print(b.toString());
}
}
Tracing the “toString” method will help you understand how the hollow square was created. But if you have any questions please do leave a message or a comment. :D
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!...