Ejercicio
Dividir si no es cero
Objetivo
Escriba un programa en java para pedir al usuario dos números y muestre su división si el segundo número no es cero; de lo contrario, mostrará "No puedo dividir"
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 the first number
System.out.print("Enter the first number: ");
// Read the first number as a double
double firstNumber = scanner.nextDouble();
// Ask the user to input the second number
System.out.print("Enter the second number: ");
// Read the second number as a double
double secondNumber = scanner.nextDouble();
// Check if the second number is not zero
if (secondNumber != 0) {
// Display the result of dividing the first number by the second
System.out.println("The result is: " + (firstNumber / secondNumber));
} else {
// If the second number is zero, display "I cannot divide"
System.out.println("I cannot divide");
}
// Close the scanner to free up resources
scanner.close();
}
}