Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package triangle;
- import java.util.Arrays;
- // třída výjimky kdy daný trojúhelník nemůže existovat. Tohle nejspíš dělat nemusíte.
- class NotATriangleException extends Exception {
- public NotATriangleException(String message) {
- super(message);
- }
- }
- public class Triangle {
- double strA, strB, strC;
- Triangle(double a, double b, double c) throws NotATriangleException {
- // kontroluje trojúhleníkovou nerovnost a kladnost parametrů
- if ((a + b <= c) || (a + c <= b) || (b + c <= a) || (a <= 0) || (b <= 0) || (c <= 0)) {
- // místo hození výjimky můžete třeba vypsat chybovou hlášku
- throw new NotATriangleException("Sides " + a + " and " + b + " and " + c + " don't make a triangle!");
- }
- strA = a;
- strB = b;
- strC = c;
- }
- Triangle(double x) throws NotATriangleException {
- this(x, x, x);
- }
- double obvod() {
- return strA + strB + strC;
- }
- boolean jePravouhly() {
- double arr[] = {strA, strB, strC};
- Arrays.sort(arr);
- //kontroluje, že platí Pythagorova věta s relativní přesností na tisíciny
- return Math.abs(Math.pow(arr[2], 2) - (Math.pow(arr[1], 2) + Math.pow(arr[0], 2))) < 0.001 * arr[0];
- }
- double obsah() {
- //implementuje Heronův vzorec viz http://www.matematika.cz/obsah-trojuhelniku
- double s = (strA + strB + strC) / 2;
- return Math.sqrt(s * (s - strA) * (s - strB) * (s - strC));
- }
- boolean jeRovnostranny() {
- //relace ekvivalence je tranzitivní, stačí kontrolovat rovnost A s B a A s C
- return (strA == strB && strA == strC);
- }
- void vypisInfo() {
- System.out.println("Trojúhelník má:");
- System.out.println("Stranu A dlouhou: " + strA);
- System.out.println("Stranu B dlouhou: " + strB);
- System.out.println("Stranu C dlouhou: " + strC);
- System.out.println("Obvod: " + this.obvod());
- System.out.println("Obsah: " + this.obsah());
- if (this.jePravouhly()) {
- System.out.print("Je");
- } else {
- System.out.print("Není");
- }
- System.out.println(" pravoúhlý.");
- if (this.jeRovnostranny()) {
- System.out.print("Je");
- } else {
- System.out.print("Není");
- }
- System.out.println(" rovnostranný.");
- }
- public static void main(String[] args) {
- // pokud nepoužíváte vyjímky, bloky try a catch nepotřebujete
- try {
- Triangle a = new Triangle(6);
- a.vypisInfo();
- } catch (NotATriangleException e) {
- System.err.println("Error: " + e.getMessage());
- }
- System.out.println();
- try {
- Triangle b = new Triangle(3, 4, 5);
- b.vypisInfo();
- } catch (NotATriangleException e) {
- System.err.println("Error: " + e.getMessage());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment