Implementation of the division algorithm in Java

<<algorithm


alg div en

import java.util.Scanner;
public class DivisionAlgorithm {
  public static void main(String[] args) {
    float x,y;
    Scanner klaw=new Scanner(System.in);
    System.out.print("x=");
    x=klaw.nextFloat();
    System.out.print("y=");
    y=klaw.nextFloat();
    if(y==0) 
      System.out.println("Can not divide by 0");
    else {
      float z;
      z=x/y;
      System.out.print("x/y=");
      System.out.println(z); 
    }
  } 
}

In the first line of the program, we indicate that we will be using the Scanner class from Java's util library. The Scanner class will be used to read input data in our program.

In Java, program execution begins with the invocation of the public static main() function contained within the class whose name matches the program's name (the program must be saved in a file named DivisionAlgorithm.java and then compiled into a DivisionAlgorithm.class file). The definition of the DivisionAlgorithm class begins on line 2 of the program.

In our example, the main() function is the program's only function. Line 3 contains the start of the main function definition, which marks the beginning of our algorithm's execution (START block (1)).

In the following line, we declare two variables, x and y, which we will use shortly. In Java, variables can be declared anywhere before their use, which is why we don't immediately declare the variable z, which might not be needed at all. On line 5, we declare and initialize the variable scanner as a Scanner object. We specify that the source of the textual data will be the System.in stream, i.e., the keyboard.

Lines 6 to 9 implement the Input/Output operation (2), where the input data—the dividend and the divisor—are retrieved.

The conditional statement on line 10 is the Decision block (3) from our algorithm. The statement checks whether y is equal to 0. If the condition is met, the instruction written on line 11 is executed (corresponding to the Input/Output block (4) in the algorithm). If the condition is not met, the instruction following the keyword else is executed; in our case, this is a compound statement enclosed in curly braces {} between lines 13 and 16. First, on line 13, we declare the variable z (now we know we'll need it), then on line 14, we calculate the quotient of x divided by y (Operation block (5)), and finally, on lines 15 and 16, we output the received result (Input/Output block (6)).

The closing curly brace } on line 18 ends the main function and, consequently, the execution of the entire program (Stop block of the algorithm (7)), while the curly brace on line 19 ends the definition of the DivisionAlgorithm class.