Created
February 23, 2012 21:32
-
-
Save randysecrist/1895172 to your computer and use it in GitHub Desktop.
Helping Dusting learn Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Triangle { | |
private int a, b, c; | |
public Triangle( int a, int b, int c ) { | |
this.a = a; | |
this.b = b; | |
this.c = c; | |
} | |
public int getSide(int side) { | |
if (side == 1) | |
return a; | |
else if (side == 2) | |
return b; | |
else if (side == 3) | |
return c; | |
else | |
throw new RuntimeException("Only three sides to a triangle!"); | |
} | |
public boolean isTriangle() { | |
if ((a < b + c) || | |
(b < c + a) || | |
(c < a + b)) { | |
// Triangle | |
return true; | |
} | |
else | |
return false; | |
} | |
public boolean isEquilateral() { | |
if ((a < b + c && b == c) || | |
(b < c + a && c == a) || | |
(c < a + b && a == b)) { | |
// Equilateral Triangle; | |
return true; | |
} | |
else | |
return false; | |
} | |
/** | |
* Is this triangle a right triangle? | |
*/ | |
public boolean isRight() { | |
// a^2 + b^2 == c^2 | |
int x = intpow(a, 2) + intpow(b, 2); | |
int y = intpow(c, 2); | |
if (x == y) | |
return true; | |
else | |
return false; | |
} | |
// calculate an exponent for a given base | |
// e.g. - 2^3 == intpow(2,3) == 8 | |
private int intpow (int base, int exp) { | |
int x = 1; | |
for( int i = 0; i < exp; i++ ) | |
x*=base; | |
return x; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
import java.util.InputMismatchException; | |
public class TriangleTest { | |
public static void main(String[] argv) { | |
// Collect User Input | |
int side1 = 0, side2 = 0, side3 = 0; | |
try { | |
System.out.println("Please enter three integers, each which represents the length of a triangle side."); | |
Scanner input = new Scanner(System.in); | |
side1 = input.nextInt(); | |
side2 = input.nextInt(); | |
side3 = input.nextInt(); | |
} | |
catch (InputMismatchException e) { | |
System.out.println("Integer Input Fail!"); | |
System.exit(1); | |
} | |
// verify user input | |
if (side1 == 0 || side2 == 0 || side3 == 0) { | |
System.out.println("Zero values for a side are not permitted!"); | |
System.exit(1); | |
} | |
Triangle t = new Triangle( side1, side2, side3 ); | |
System.out.printf("Triangle Values: (%d, %d, %d)\n", t.getSide(1), t.getSide(2), t.getSide(3)); | |
System.out.println("Triangle isRight: " + t.isRight()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment