Exercise
Square
Objetive
Write a java program that prompts the user to enter a number and a width, and displays a square of that width, using that number for the inner symbol, as shown in this example:
Enter a number: 4
Enter the desired width: 3
444
444
444
Example Code
// Importing the Scanner class to handle input from the user
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Declare variables for the number and width
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt(); // Read the number from the user
System.out.print("Enter the desired width: ");
int width = sc.nextInt(); // Read the width from the user
// Loop to display the square with the given width
for (int i = 0; i < width; i++) {
// Loop to display the number in each row
for (int j = 0; j < width; j++) {
System.out.print(number); // Print the number without a newline
}
System.out.println(); // Move to the next line after each row
}
}
}