Implementation of the linear equation solving algorithm in Java

 <<algorithm

example of an algorithm solving the linear equation

import java.util.Scanner;
public class Linear{
  public static void main(String[] args) {
    float a,b;
    Scanner key=new Scanner(System.in);
    System.out.print("a=");
    a=key.nextFloat();
    System.out.print("b=");
    b=key.nextFloat();
    if(a==0)
      if(b==0)
        System.out.println("identity equation");
      else
        System.out.println("contrary equation");
    else {
      float x;
      x=-b/a;
      System.out.print("x=");
      System.out.println(x);
    }
  }
}

 
 

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 Linear.java and then compiled into a Linear.class file). The definition of the Linear 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, a and b, 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 x, 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 coefficients a and b of the equation—are retrieved.

The conditional statement on line 10 is the Decision block (3) from our algorithm. The statement checks whether the coefficient a is equal to 0. If the condition is met, the instructions contained in lines 11 through 14 are executed (corresponding to the Decision block (4) and Input/Output blocks (5) and (6) 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 15 and 20. First, on line 16, we declare the variable x (now we know we'll need it), then on line 17, we calculate the solution to the equation x=−b/a (Operation block (7)), and finally, on lines 18 and 19, we output the received result (Input/Output block (8)).

The closing curly brace } on line 21 ends the main function and, consequently, the execution of the entire program (Stop block of the algorithm (9)), while the curly brace on line 22 ends the definition of the Linear class.