Exercise
Many divisions
Objetive
Write a java program that asks the user for two numbers and displays their division and remainder of the division. If 0 is entered as the second number, it will warn the user and end the program if 0 is entered as the first number. Examples:
First number? 10
Second number? 2
Division is 5
Remainder is 0
First number? 10
Second number? 0
Cannot divide by 0
First number? 10
Second number? 3
Division is 3
Remainder is 1
First number? 0
Bye!
Example Code
// Importing the Scanner class to handle input from the user
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Declare variables for the two numbers entered by the user
int firstNumber;
int secondNumber;
// 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("First number? ");
firstNumber = scanner.nextInt();
// Check if the first number is 0, then exit the program
if (firstNumber == 0) {
System.out.println("Bye!");
return; // Exit the program if the first number is 0
}
// Ask the user to input the second number
System.out.print("Second number? ");
secondNumber = scanner.nextInt();
// Check if the second number is 0 and handle the division by 0 case
if (secondNumber == 0) {
System.out.println("Cannot divide by 0");
} else {
// Calculate the division and remainder
int division = firstNumber / secondNumber;
int remainder = firstNumber % secondNumber;
// Display the results of the division and remainder
System.out.println("Division is " + division);
System.out.println("Remainder is " + remainder);
}
}
}