Click here to Skip to main content
15,897,704 members
Articles / Programming Languages / Java

Area of a Triangle in the Cartesian Coordinate System

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
27 Oct 2012CPOL 21.7K   2   2  
For absolute beginners in Java
/* Author: @TharieHimself */
import java.util.Scanner;
public class Triangle{
	
	public static void main(String[] args) {
		
		Triangle tri = new Triangle();
		tri.calcArea();
		
	}
	public void calcArea(){
	     Scanner scan = new Scanner(System.in);
	     
	     double[][] coordinates = new double[3][2];
	     double[] sides = new double[3];
	     int count = 0;
	     String axis;
	     
	     for(int r=0; r<3; r++)
	     {
	    	 for(int c=0; c<2;c++){
	    		 count++;
	    		 axis = (count % 2 == 0) ? "Y" : "X";
	    		 System.out.print("Enter "+axis+" Coordinate for Node "+count+": ");
	    		 coordinates[r][c] = scan.nextDouble();
	    	 }
	     }
	     
	     /* THIS PART CAN NOT BE ACHIEVED THROUGH A FOR LOOP; THERE IS NO PATTERN */ 
	     sides[0] = Math.sqrt((Math.pow((coordinates[0][0]- coordinates[1][0]), 2)) + Math.pow((coordinates[0][1] - coordinates[1][1]), 2));
	     sides[1] = Math.sqrt((Math.pow((coordinates[1][0]- coordinates[2][0]), 2)) + Math.pow((coordinates[1][1] - coordinates[2][1]), 2));
	     sides[2] = Math.sqrt((Math.pow((coordinates[2][0]- coordinates[0][0]), 2)) + Math.pow((coordinates[2][1] - coordinates[0][1]), 2));
	     
	     double s = (sides[0]+ sides[1]+ sides[2])/2;
	     double area = Math.sqrt(s*(s-sides[0])*(s-sides[1])*(s-sides[2]));
	     
	     /* THIS WILL ROUND OFF THE AREA TO THREE DECIMAL PLACES */
	     double roundOff = Math.round(area * 1000.0) / 1000.0;
	  	     
	     if(!(area > 0))
	    	 System.out.println("\nYour Triangle does not exist!");
	     else
	     System.out.println("\nArea of your Triangle is: "+roundOff);      	     
	}

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions