Sunday, 22 June 2008

Basic Java Programming 1

I will just put in something that I revise through today. The question is to programme a application to calculate the area of a Trapezoid. The given formula as follows:
Area of Trapezoid= 1/2 x (breadth1+breadth2) x height

The format as follows:

------ Start of Coding ------
package practice ; // practice is the project name
import javax.swing.JOptionPane; //to import the JOptionPane template
public class TrapezoidProgram { //represents the class name called TrapezoidProgram
public static void main(String args[]) { // main method. Its a standard format.

String s1 = JOptionPane.showInputDialog("Input b1"); //create a storage(s1) for b1
String s2 = JOptionPane.showInputDialog("Input b2"); //create a storage(s2) for b2
String s3 = JOptionPane.showInputDialog("Input h"); //create a storage(s3) for b3

int b1 = Integer.parseInt(s1); // to declare b1 as an integer for storage1
int b2 = Integer.parseInt(s2); // to declare b2 as an integer for storage2
double h = Double.parseDouble(s3); // to declare h as a double for storage3

double trapezoidArea = (0.5) * (b1 + b2) * h; // Output of Area as double value
System.out.print("b1\t:"+b1+"\nb2\t:"+b2+"\nh\t:"+h+"\nArea\t:"+trapezoidArea); // Prints out the output

}

}
------End Of Coding ------

The output of this coding will be exactly like this:

b1 : 5
b2 : 7
h : 3.0
Area: 18.0


Additional Info:
Integer = Single number, e.g. 3, 10, 256, etc
Double = Single number with decimal places, e.g. 1.0, 14.5, 138.7, etc

No comments: