Introduction to Programming in Java - Computer engineering - C# php asp .Net SAP SQL

Friday, February 29, 2008

Introduction to Programming in Java

I will explain programming in Java on an example. In this example we will calculate the roots of an equation whose solution is not a complex root.Our program will give an output if the root of the equation is complex as COMPLEX ROOT!!! User will enter the coefficients of the equation.

Let us start to examine the code of the program:

import javax.swing.JOptionPane; --> This code is to activate JOptionPane function of Java.

public class hmwrk2_1{ ---> Firstly we create our class which our object will be included

public static void main (String[] args) { --->We are starting to write the main function of our code

int a, b, c; ---> Now we declare our variables which i have explained in Programming Languages article

a=Integer.parseInt(JOptionPane.showInputDialog(null,"ax^2 + bx + c \n please enter the coefficient a:")); ---> We are assigning variable a to the value which user enters




b=Integer.parseInt(JOptionPane.showInputDialog(null,"ax^2 + bx + c \n please enter the coefficient b:")); --->we are assigning the value which user enters to the variable b again

c=Integer.parseInt(JOptionPane.showInputDialog(null,"ax^2 + bx + c \n please enter the constant c:")); --->same process as above.

double x1,x2; ---> We are declaring 2 double values for roots of the equation

double delta=(b*b)-(4*a*c); --->We are declaring double delta and setting it to a equation in formula

if(delta<0){> If delta value that we calculated by the values user have entered is smaller than zero we we get the warning complex root!!!

JOptionPane.showMessageDialog(null,"COMPLEX ROOT!!!"); }


else if (delta==0){ --->If delta value equals to zero
x1 = x2 = -b/(2*a); ---> We calculate the roots as in formula.

JOptionPane.showMessageDialog(null,"root= "+x1);---> And printing one of them to the screen


}

else { ---> If the value of delta is bigger than zero
x1=(-b+(Math.sqrt(delta)))/(2*a); ---> We set x1 and x2 variables as in formula.

x2=(-b-(Math.sqrt(delta)))/(2*a);

JOptionPane.showMessageDialog(null,"root1= "+x1+"\nroot2= "+x2); ---> And printing both of them to the screen


}
}
}

No comments: