Write a Java program to Demonstrate the Math.floorDiv() method
This Java program reads two integers from the user and then uses the Math.floorDiv method to divide them and return the quotient (i.e., the result of the division rounded down to the nearest integer). Here's a breakdown of the program:
- The import java.util.*; statement imports the java.util package, which contains the Scanner class that is used to read input from the user.
- The public class Add_Exact statement declares a public class called Add_Exact, which is the name of the Java file that this program is saved in.
- The public static void main(String[] args) method is the entry point for the program. It takes an array of strings as an argument, but in this program, that argument is not used.
- Inside the main method, a new Scanner object called input is created to read input from the user.
- Two integer variables n1 and n2 are declared and initialized to 0.
- The program prompts the user to enter two integers using System.out.print and reads them using input.nextInt().
- The Math.floorDiv(n1, n2) method is used to divide n1 by n2 and return the quotient rounded down to the nearest integer.
- The result is then printed to the console using System.out.print.
Note that if the user enters 0 as the second number, the program will throw an ArithmeticException since division by 0 is not allowed.
Source Code
import java.util.*;
public class Add_Exact
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n1 = 0;
int n2 = 0;
System.out.print("Enter the Number 1 : ");
n1 = input.nextInt();
System.out.print("Enter the Number 2 : ");
n2 = input.nextInt();
System.out.print("Result : " + Math.floorDiv(n1, n2));
}
}
Output
Enter the Number 1 : 84
Enter the Number 2 : 56
Result : 1