Exercise
Multiply if not zero
Objetive
Write a java program to ask the user for a number; if it is not zero, then it will ask for a second number and display their sum; otherwise, it will display "0"
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 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();
}
}