113k views
2 votes
19. Squares. Write a program class named SquareDisplay that asks the user for a positive integer no greater than 15. The program should then display a square on the screen using the character ‘X’. The number entered by the user will be the length of each side of the square. For example, if the user enters 5, the program should display the following: XXXXX XXXXX XXXXX XXXXX XXXXX INPUT and PROMPTS. The program prompts for an integer as follows: "Enter an integer in the range of 1-15: ". OUTPUT. The output should be a square of X characters as described above. CLASS NAMES. Your program class should be called SquareDisplay java

User Gil Fink
by
5.0k points

1 Answer

2 votes

Answer:

Step-by-step explanation:

import java.util.Scanner;

public class SquareDisplay {

public static void main(String []args){

// Scanner is used to get value from command line

Scanner console = new Scanner(System.in);

System.out.print("Enter an integer in the range of 1-15:");

int number = console.nextInt();

// check if number is greater then 15 or less then 1 then return error message

if(number>0 && number<=15){

System.out.println("Error :Wrong Input");

return;

}

for( int i=0; i< number; i++){

for( int j =0; j<number; j++){

System.out.print("X");

}

System.out.print(" ");

}

}

}

Code Explanation

As we want to show the square of X's we need to execute 2 nested for loop to achieve the target result. Outer for loop will determine that how many times we need to show the group of X's.

And the inner for loop will actually display's number of X's for every outer loop iteration.

Output

Case 1:

Enter an integer in the range of 1-15:5

XXXXX XXXXX XXXXX XXXXX XXXXX

Case 2:

Enter an integer in the range of 1-15:16

Error :Wrong Input

Case 3:

Enter an integer in the range of 1-15:2

XX XX

User A Srinivas
by
5.8k points