Exercise
Formats
Objetive
Write a java program to ask the user for a number and display it four times in a row, separated with blank spaces, and then four times in the next row, with no separation. You must do it two times: first using Console.Write and then using {0}.
Example:
Enter a number: 3
3 3 3 3
3333
3 3 3 3
3333
Example Code
// Importing the Scanner class to handle input from the useimport java.util.Scanner; // Import Scanner class for input
public class Program {
// Main entry point of the program
public static void main(String[] args) {
// Create a scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Ask the user to input a number
System.out.print("Enter a number: ");
// Read the user's input as an integer
int number = scanner.nextInt();
// Print the number four times in a row, separated by spaces using System.out.print
System.out.print(number + " " + number + " " + number + " " + number);
System.out.println(); // Move to the next line
// Print the number four times in a row, without any separation using System.out.print
System.out.print(Integer.toString(number) + Integer.toString(number) + Integer.toString(number) + Integer.toString(number));
System.out.println(); // Move to the next line
// Print the number four times in a row, separated by spaces using String.format
System.out.println(String.format("%d %d %d %d", number, number, number, number));
// Print the number four times in a row, without any separation using String.format
System.out.println(String.format("%d%d%d%d", number, number, number, number));
// Close the scanner to free up resources
scanner.close();
}
}