Write two programs a class SquareGame.java (55 points) and a TestGame.java (45 p
ID: 3720264 • Letter: W
Question
Write two programs a class SquareGame.java (55 points) and a TestGame.java (45 points).
Part1:
Write a class SquaresGame.java that accepts one integer and displays a filled or hollow square using asterisks. The class has two separate methods one that displays the filled square and one that displays a hollow square e.g. for sideLength 5.
***** *****
***** * *
***** * *
***** * *
***** *****
The class must include:
One instance variable sideLength (5 points)
Two constructs (10 points)
Mutators and Accessors (10 points)
fillSquare() (15 points)
hollowSquare() (15 points)
Part2:
TestGame.java will ask the user to enter a positive number between 1-10 and whether they want to draw a filled or hollow square. The program must allow the user the choice of continuing to play or quite the game.
The program must include:
Input validation. User input must be a positive digit from 1 – 10. (10 points)
Input validation. User input must choose between two options only ‘filled’ and ‘hollow’. You can create a menu 1 for filled and 2 for square. Or you can validate input using string operators. (15 points)
Include user prompts that guide user input even during input validation (10 points)
Use a do while loop. The program continues until the user decides to quit the game (10)
Explanation / Answer
TestGame.java
import java.util.Scanner;
public class TestGame {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer (1-10): ");
int n = scan.nextInt();
while(n<1||n>10){
System.out.println("Invalid Input. Enter an integer (1-10): ");
n = scan.nextInt();
}
System.out.println("Menu: 1. Filled 2. Hollow 3. Quit Enter your choice: ");
int choice = scan.nextInt();
SquareGame s = new SquareGame(n);
while(choice!=3){
if(choice==1){
s.printFullSquare();
} else if(choice==2){
s.printHollowSquare();
} else {
System.out.println("Invalid choice.");
}
System.out.println("Menu: 1. Filled 2. Hollow 3. Quit Enter your choice: ");
choice = scan.nextInt();
}
}
}
SquareGame.java
public class SquareGame {
private int sideLength ;
public SquareGame(int n) {
sideLength=n;
}
public void printFullSquare() {
for(int i=1;i<=sideLength;i++) {
for(int j=1;j<=sideLength;j++){
System.out.print("*");
}
System.out.println();
}
}
public void printHollowSquare() {
for(int i=1;i<=sideLength;i++) {
for(int j=1;j<=sideLength;j++){
if(i==1||i==sideLength||j==1||j==sideLength)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
Output:
Enter an integer (1-10):
5
Menu:
1. Filled
2. Hollow
3. Quit
Enter your choice:
1
*****
*****
*****
*****
*****
Menu:
1. Filled
2. Hollow
3. Quit
Enter your choice:
2
*****
* *
* *
* *
*****
Menu:
1. Filled
2. Hollow
3. Quit
Enter your choice:
3
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.