Ejercicio
Formatos
Objetivo
Escriba un programa en java para pedir al usuario un número y muestre ir cuatro veces seguidas, separadas con espacios en blanco y, a continuación, cuatro veces en la fila siguiente, sin separación. Debe hacerlo dos veces: primero usando Console.Write y luego usando {0}.
Código de Ejemplo
// 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();
}
}