Ejercicio
Multiplicar si no es cero
Objetivo
Escriba un programa en java para pedir al usuario un número; si no es cero, entonces pedirá un segundo número y mostrará su valor; de lo contrario, mostrará "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 the first number
System.out.print("Enter a number: ");
// Read the first number as a double
double firstNumber = scanner.nextDouble();
// Check if the first number is not zero
if (firstNumber != 0) {
// Ask the user to input the second number
System.out.print("Enter another number: ");
// Read the second number
double secondNumber = scanner.nextDouble();
// Display the result of multiplying the two numbers
System.out.println("The result is: " + (firstNumber * secondNumber));
} else {
// If the first number is zero, display 0
System.out.println("0");
}
// Close the scanner to free up resources
scanner.close();
}
}