Exercise
Divide if not zero
Objetive
Write a java program to ask the user for two numbers and display their division if the second number is not zero; otherwise, it will display "I cannot divide".
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 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();
}
}