Skip to content

Instantly share code, notes, and snippets.

@iGlitch
Created July 31, 2014 01:40
Show Gist options
  • Save iGlitch/c9e364428b52e4ea3295 to your computer and use it in GitHub Desktop.
Save iGlitch/c9e364428b52e4ea3295 to your computer and use it in GitHub Desktop.
Write a program that prompts the user to enter three points of a triangle and displays the angles in degrees. Round the value to keep two digits after the decimal point.
import java.awt.Point;
import java.io.IOException;
public class Angles {
public static void main(String[] args) throws IOException {
//1 1 6.5 1 6.5 2.5
double[] numbers = new double[0];
while(numbers.length != 6) try {
System.out.print("Enter three points: ");
numbers = parseInput(readInput());
//catch error on incorrect number of inputs
if(numbers.length != 6) {
System.out.println("Incorrect number of inputs. 6 numbers are required, 2 for each point.");
}
} catch(NumberFormatException e) {
//catch error on non-number input
String msg = e.getMessage();
msg = msg.substring(msg.indexOf('"'), msg.lastIndexOf('"')+1);
System.out.printf("The input %s is not a recongizable number.\n",msg);
}
// Calculate sides
double a = Point.distance(numbers[2], numbers[3], numbers[4], numbers[5]);
double b = Point.distance(numbers[0], numbers[1], numbers[4], numbers[5]);
double c = Point.distance(numbers[0], numbers[1], numbers[2], numbers[3]);
// Calculate angles
double A = Math.acos((a*a-b*b-c*c)/(-2.0*b*c));
double B = Math.acos((b*b-a*a-c*c)/(-2.0*a*c));
double C = Math.acos((c*c-b*b-a*a)/(-2.0*a*b));
//Convert angles to degrees
A = Math.toDegrees(A);
B = Math.toDegrees(B);
C = Math.toDegrees(C);
System.out.printf("The three angles are %.2f %.2f %.2f\n",A,B,C);
}
public static String readInput() throws IOException {
byte[] buffer = new byte[64];
int count = System.in.read(buffer);
String input = new String(buffer,0,count);
return input;
}
public static double[] parseInput(String input) {
String[] split = input.split(" +");
double[] output = new double[split.length];
for(int i = 0; i < split.length; ++i)
output[i] = Double.parseDouble(split[i]);
return output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment