Advertisement
brilliant_moves

HeronsFormula.java

Jan 5th, 2014
316
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.58 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.Scanner;
  3.  
  4. public class HeronsFormula {
  5.  
  6.     /**
  7.     *   Program:    HeronsFormula.java
  8.     *   Purpose:    Yahoo! Answers triangle area question
  9.     *   Creator:    Chris Clarke
  10.     *   Created:    05.01.2014
  11.     */
  12.  
  13.     public static void main(String[] args) {
  14.         int n;  // number of triangles read from file
  15.         int a, b, c;
  16.         String area;
  17.  
  18.         try {
  19.             // create scanner to read from file
  20.             Scanner fileScan = new Scanner(new File("Triangles.txt"));
  21.             /*
  22.                 Sample file (need to save as "Triangles.txt"):
  23.  
  24.                 9
  25.                 7 8 9
  26.                 9 9 12
  27.                 6 5 21
  28.                 24 7 25
  29.                 13 12 5
  30.                 50 40 30
  31.                 10 10 10
  32.                 82 34 48
  33.                 4 5 6
  34.             */
  35.  
  36.             // read lead value indicating the number of triangles to be evaluated
  37.             n = fileScan.nextInt();
  38.             System.out.println("A\tB\tC\tAREA");
  39.             for (int i=0; i<n; i++) {
  40.                 a = fileScan.nextInt();
  41.                 b = fileScan.nextInt();
  42.                 c = fileScan.nextInt();
  43.  
  44.                 System.out.printf("%d\t%d\t%d\t", a, b, c);
  45.                 calculateArea(a, b, c);
  46.             } // end for
  47.         } catch (FileNotFoundException e) {
  48.             System.out.println("File not found!");
  49.             return;
  50.         } // end try/catch
  51.  
  52.     } // end main()
  53.  
  54.     public static void calculateArea(int a, int b, int c) {
  55.         double s;
  56.         double temp;
  57.         double area = 0.0;
  58.  
  59.         s = (a + b + c) / 2.0;
  60.         temp = s*(s-a)*(s-b)*(s-c);
  61.         if (temp < 0) {
  62.             System.out.println("This is not a triangle");
  63.             return;
  64.         } // end if
  65.         area = Math.sqrt(temp);
  66.         if (area==0) {
  67.             System.out.println("This is not a triangle");
  68.             return;
  69.         } // end if
  70.         System.out.printf("%2.4f%n", area);
  71.     } // end calculateArea()
  72. } // end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement