Calculating the area of a triangle - java

I am new to Java. I am trying to calculate the area of a triangle using the formula:
s = (side 1 + side 2 + side 3)/2
area = square root (side (side - side 1)(side - side2)(side - side3).
If the user enter the three point as:
1.5 -3.4 4.6 5 9.5 -3.4 then the area of the triangle should be 33.6. However, my program runs, but it's giving me an incorrect answer. Below is my code.
// Import Java Scanner
import java.util.Scanner;
import java.lang.Math;
public class Ex_2_19 {
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
float side = 0;
float area1 = 0;
float area2 = 0;
float area3 = 0;
float area4 = 0;
float calculatedarea = 0;
//Prompt the user to enter three points of a triangle
System.out.println("Enter point x1:");
System.out.println("Enter point y1:");
System.out.println("Enter point x2:");
System.out.println("Enter point y2:");
System.out.println("Enter point x3:");
System.out.println("Enter point y3:");
//Define the variables
float Pointx1 = input.nextFloat();
float Pointy1 = input.nextFloat();
float Pointx2 = input.nextFloat();
float Pointy2 = input.nextFloat();
float Pointx3 = input.nextFloat();
float Pointy3 = input.nextFloat();
//Formula to calculate the area of a triangle
side = (Pointx1 + Pointy1 + Pointx2 + Pointy2 + Pointx3 + Pointy3) / 2;
area1 = side - (Pointx1 + Pointy1);
area2 = side - (Pointx2 + Pointy2);
area3 = side - (Pointx3 + Pointy3);
area4 = side * area1 * (area2) * (area3);
calculatedarea = (float) (Math.sqrt(area4));
//calculatedarea = (float) (Math.sqrt(area1)*(area2) * (area3));
//Print result
System.out.println("The area of the triangle is " + calculatedarea);
}
}

You are trying Heron's Formula - note that a, b, c are the euclidean distance between the points, thus will need to be computed by sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)), etc., not just the sum of differences.

Related

How to convert double x1 = input.nextDouble(); into an array? [duplicate]

This question already has answers here:
how to take user input in Array using java?
(9 answers)
Closed 1 year ago.
/*
(Geometry: area of a triangle) Write a program that prompts the user to enter
three points (x1, y1), (x2, y2), (x3, y3) of a triangle and displays its area.
*/
import java.util.Scanner;
public class Exercise_02_19 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter three points
System.out.print("Enter three points for a triangle: ");
double x1 = input.nextDouble();
double y1 = input.nextDouble();
double x2 = input.nextDouble();
double y2 = input.nextDouble();
double x3 = input.nextDouble();
double y3 = input.nextDouble();
// Compute the area of a triangle
double side1 = Math.pow(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2), 0.5);
double side2 = Math.pow(Math.pow(x3 - x2, 2) + Math.pow(y3 - y2, 2), 0.5);
double side3 = Math.pow(Math.pow(x1 - x3, 2) + Math.pow(y1 - y3, 2), 0.5);
double s = (side1 + side2 + side3) / 2;
double area = Math.pow(s * (s - side1) * (s - side2) * (s - side3), 0.5);
// Display result
System.out.println("The area of the triangle is " + area);
}
}
I am learning the Java coding language and currently stuck on a question. How can I convert double x1 = input.nextDouble(); into an array that does x1 to 3 and y1 to 3? We are currently using the Introduction to Java Programming and Data Structures Twelfth Edition and even taking the time to read and understand what is going on is hard for me to comprehend. If there is someone with Java knowledge to help what went wrong and point me in the right direction that would be great. Thank you!
double[] x = new double[3];
double[] y = new double[3];
Now you can access x1 to x3 as x[0] to x[2] and similarly for y.

Drawing triangles with java using trigonometry

What I'm trying to do is create a program which take a side length and two angles and produces a triangle drawn using the AWT library.
I'm having trouble working out the logic to use the trigonometric ratios to produce the x and y points of the polygon.
for example, given two angles and a side, I'm attempting to calculate the next x and y points to draw the lines to.
Currently, I've just got some arbitrary points defined to draw a triangle at the moment.
the code block below the graphics is the math for working out all the sides to the triangle
Could anybody be of assistance?
Here is my code. It is badly written. It's mostly just me experimenting and learning more about java.
import javax.swing.*;
import java.awt.*;
import java.math.*;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
public class program{
public static void main (String[] args) {
JFrame frame = new JFrame();
CustomPaintComponent c = new CustomPaintComponent();
frame.add(c);
frame.setSize(1000,1000);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setTitle("Triangle");
frame.setVisible(true);
}
}
class CustomPaintComponent extends Component {
public void paint(Graphics g){
Graphics2D G2D = (Graphics2D)g;
int[] xpoints = { 500, 750 , 1000 , 500};
int[] ypoints = { 500 , 250 , 500 , 500};
G2D.drawPolygon(xpoints,ypoints,4);
}
public Triangle calc(){
double s1,a1,a2;
s1 = Integer.parseInt(JOptionPane.showInputDialog("Please enter side 1"));
a1 = Integer.parseInt(JOptionPane.showInputDialog("Please enter angle 1"));
a2 = Integer.parseInt(JOptionPane.showInputDialog("Please enter angle 2"));
double s2 = ((s1/Math.sin(Math.toRadians(a1))) * Math.sin(Math.toRadians(a2)));
System.out.println(s1/Math.sin(a1));
System.out.println(Math.sin(a2));
double a3 = 180 - (a1 + a2);
double s3 = Math.pow(s2, 2) + Math.pow(s1, 2) - (2 * s2 * s1 * Math.cos(Math.toRadians(a3)));
s3 = Math.sqrt(s3);
Math.toDegrees(a1);
Math.toDegrees(a2);
Math.toDegrees(a3);
System.out.println("side 1 is " + s1 + "side 2 is " + s2 + " and the third angle is: " + a3 + " and the third side length is: " + s3);
Triangle Triangle = new Triangle(s1,s2,s3,a1,a2,a3);
return Triangle;
}
}
class Triangle{
double s1,s2,s3,a1,a2,a3;
Triangle(double s1, double s2, double s3, double a1, double a2, double a3){
this.s1 = s1;
this.s2 = s2;
this.s3 = s3;
this.a1 = a1;
this.a2 = a2;
this.a3 = a3;
}
}
The three rules that a triangle must satisfy:
The angles always add to 180°
A + B + C = 180 degrees
Law of Sines (The Sine Rule) a/sin(A) = b/sin(B) = c/sin(C)
Note: Angle A is opposite to side a, B is opposite to side b, and C is opposite to side c.
Law of Cosines (The Cosine Rule) c^2 = a^2 + b^2 − 2ab*cos(C)
So, let's say you have a triangle XYZ.
The angle opposite to side x = X (=YXZ), the angle opposite to side y = Y (=XYZ), and the angle opposite to side z = Z (=XZY).
The input given by the user is the two angles and the side in between them.
Let the input be:
Angle X = 76 degrees
Angle Y = 34 degrees
Side z = 9 cm
First, find the third angle Z by using the first property.
Angle Z = 180 - X - Y
= 180 - 76 - 34
= 70 degrees
Now, using the Law of Sines, find the sides x and y.
x/sin(X) = z/sin(Z)
=> x/sin(76°) = 9/sin(70°)
=> x = (9/sin(70°)) × sin(76°)
=> x = 9.29 cm
y/sin(Y) = z/sin(Z)
=> y/sin(34°) = 9/sin(70°)
=> y = (9/sin(70°)) × sin(34°)
=> y = 5.36 cm
To code it:
static void printSidesOfTriangle(double side3, double angle1, double angle2){
// The sum of all the angles of triangle is 180 degrees
double angle3 = 180 - angle1 - angle2;
// Converting the angles from degrees to radians
angle1 = Math.toRadians(angle1);
angle2 = Math.toRadians(angle2);
angle3 = Math.toRadians(angle3);
double ratio = side3/(Math.sin(angle3));
double side1 = ratio*(Math.sin(angle1));
double side2 = ratio*(Math.sin(angle2));
System.out.println("The sides of the traingle are: " +
String.valueOf(side1) + ", " +
String.valueOf(side2) + ", and " +
String.valueOf(side3) + ".");
}
And to get the x and y coordinates of each point of the triangle, you need to have some more information as there can be multiple triangles possible with 3 sides on a 2D plane.
Else, you may assume one of the coordinates to be (0,0) and find slopes of both sides.
This way, you will get the x and y coordinates of the remaining point as you have the lengths of these two segments.
Let's assume:
Angle X = 76 degrees
Angle Y = 34 degrees
Angle Z = 70 degrees
Side x = 9.29 cm
Side y = 5.36 cm
Side z = 9.00 cm
Assume three vertices to be (x1,y1), (x2,y2), and (x3,y3).
Check out this LINK
In this way, you can get the x and y coordinates of the remaining vertex.
To code it:
//printVerticesOfTriangle(5.35,9.29,9.0,34,76,70);
//printVerticesOfTriangle(3,4,5,37,53,90);
static void printVerticesOfTriangle(double side1, double side2, double side,
double angle1, double angle2, double angle3)
{
// side1 opposite to angle1
// side2 opposite to angle2
// side3 opposite to angle3
// The vertices are (x1,y1), (x2,y2) and (x3,y3)
double x1 = 0;
double y1 = 0;
double x2 = 0;
double y2 = 0;
double x3 = 0;
double y3 = 0;
// If an angle is 90 degrees, keep that vertex as the origin.
if(angle1==90){
x1 = 0;
y1 = 0;
x2 = side2;
y2 = 0;
x3 = 0;
y3 = side3;
}
else if(angle2==90){
x2 = 0;
y2 = 0;
x1 = side1;
y1 = 0;
x3 = 0;
y3 = side3;
}
else if(angle3==90){
x3 = 0;
y3 = 0;
x1 = side1;
y1 = 0;
x2 = 0;
y2 = side2;
}
// If it is not a right-angled triangle
else{
// Converting the angles from degrees to radians
angle1 = Math.toRadians(angle1);
angle2 = Math.toRadians(angle2);
// For the slope, angle with the positive x-axis is considered
angle3 = Math.toRadians(180-angle3);
x1 = 0;
y1 = 0;
x3 = side2;
y3 = 0;
// Vertex (x2,y2) has to be calculated
x2 = x3*Math.tan(angle3)/(Math.tan(angle1)-Math.tan(angle2));
y2 = x2*Math.tan(angle1);
}
System.out.println("The vertices of the triangle are: " +
"(" + String.format("%.2f",x1) + "," + String.format("%.2f",y1) + "), " +
"(" + String.format("%.2f",x2) + "," + String.format("%.2f",y2) + "), " +
"(" + String.format("%.2f",x3) + "," + String.format("%.2f",y3) + ")");
}

(java) Decide if a line intercepts a circle

So, I need to write a program that decides whether a line intercepts a circle or not. Specific interception coordinates are not required, and simply being touching the circle or being tangent to it causes interception as well. Apologies if this has been asked before, but I couldn't find anything that suited my problem. Maybe I didn't look hard enough.
import java.util.Scanner;
public class LineCircle_Intersection {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double p1x, p2x, p1y, p2y, cx, cy, r;
System.out.print("Enter p1x: ");
p1x = in.nextDouble();
System.out.print("Enter p1y: ");
p1y = in.nextDouble();
System.out.print("Enter p2x: ");
p2x = in.nextDouble();
System.out.print("Enter p2y: ");
p2y = in.nextDouble();
System.out.print("Enter cx: ");
cx = in.nextDouble();
System.out.print("Enter cy: ");
cy = in.nextDouble();
System.out.print("Enter r: ");
r = in.nextDouble();
if ((p1x - cx < r) && (p1y - cy < r))
System.out.println("The line intersects the circle.");
else if ((p2x - cx < r) && (p2y - cy < r))
System.out.println("The line intersects the circle.");
else
System.out.println("The line does not intersect the circle.");
}
}
I've been working on an alternate route that uses line and circle formulas instead of the input points, but it's kind of a mess and I'm not sure where I'm going with it.
We can write the equation for the line as y-p1y = m (x-p1x), where m = (p2y-p1y)/(p2x-p1x)
then y = m(x-p1x) + p1y (1)
We can write the equation for the circle as (x-cx)^2 + (y-cy)^2 = r^2 (2)
If we plug (1) into (2) we get:
x^2 (1+m) + x (-2a+2cm-2dm-2bm) + a^2-2cmb+2dmb+mb^2+c^2-2cd+d^2-r^2=0
where
a = cx
b = p1x
c = p1y
d = cy
let
a' = (1+m)
b' =(-2a+2cm-2dm-2bm)
c' = a^2-2cmb+2dmb+mb^2+c^2-2cd+d^2-r^2
we know then that the line and the circurfence touch each other if
b'^2-4a'c' >= 0

Finding The Area Of A Triangle

I have a question that I would like to ask you. In my book for java programming, it asks me to write a program that finds the area of a triangle given 3 points. I tried many ways but I could never get the right answer. Can you please give me a solution to this problem. Thanks! Here is the question:
Here is my code:
import java.util.Scanner;
public class shw2point15 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter three points for a triangle:");
double x1 = input.nextDouble();
double y1 = input.nextDouble();
double x2 = input.nextDouble();
double y2 = input.nextDouble();
double x3 = input.nextDouble();
double y3 = input.nextDouble();
double s = ((x1 + y1) + (x2 + y2) + (x3 + y3)) / 2;
double area = Math.sqrt(s * (s - (x1 - y1)) * (s - (x2 - y2)) * (s - (x3 - y3)));
System.out.println("The area of the triangle is " + area);
}
}
The reason you're not getting a correct answer is because you are not finding the sides correctly. However, after finding the side length you can get the answer. Here is what I did:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter three points for a triangle:");
//Store the values in an array.
double[] xCoordinates = new double[3];
double[] yCoordinates = new double[3];
double[] sides = new double[3];
// Input the values into the array
xCoordinates[0] = input.nextDouble();
yCoordinates[0] = input.nextDouble();
xCoordinates[1] = input.nextDouble();
yCoordinates[1] = input.nextDouble();
xCoordinates[2] = input.nextDouble();
yCoordinates[2] = input.nextDouble();
// Find the side length from the input. There probably are better ways to do this.
sides[0] = Math.sqrt(Math.pow(xCoordinates[0]-xCoordinates[1], 2)+Math.pow(yCoordinates[0]-yCoordinates[1], 2));
sides[1] = Math.sqrt(Math.pow(xCoordinates[1]-xCoordinates[2], 2)+Math.pow(yCoordinates[1]-yCoordinates[2], 2));
sides[2] = Math.sqrt(Math.pow(xCoordinates[2]-xCoordinates[0], 2)+Math.pow(yCoordinates[2]-yCoordinates[0], 2));
// Find s from the sides
double s = ( sides[0]+sides[1]+sides[2] )/2;
// Find the area.
double area = Math.sqrt(s*( s-sides[0] )*( s-sides[1] )*( s-sides[2] ));
// Print the area
System.out.println("The area of the triangle is "+area);
// Output~~~~~~~~~~~~~~~
//Enter three points for a triangle:
// 1.5
// -3.4
// 4.6
// 5
// 9.5
// -3.4
// The area of the triangle is 33.600000000000016
}'

Having issues with rounding numbers

import java.util.Scanner;
public class clockwise {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the coordinates in a clowise order");
System.out.println("Enter the GPS coordinates for the 1st city: ");
double coordinateX1 = input.nextDouble();
double coordinateY1 = input.nextDouble();
System.out.println("Enter the GPS coordinates for the 2nd city: ");
double coordinateX2 = input.nextDouble();
double coordinateY2 = input.nextDouble();
System.out.println("Enter the GPS coordinates for the 3rd city: ");
double coordinateX3 = input.nextDouble();
double coordinateY3 = input.nextDouble();
System.out.println("Enter the GPS coordinates for the 4th city: ");
double coordinateX4 = input.nextDouble();
double coordinateY4 = input.nextDouble();
//
double earthRadius = 6371.01;
// Get distance
// distance=(radius)arccos(sin(x1)sin(x2)+cos(x1)cos(x2)cos( y1−y2))
// ****************************************************************************1
// 1 35.2270869 -80.8431267
double distance1 = (earthRadius)
* Math.acos(Math.sin(coordinateX1) * Math.sin(coordinateX2))
+ Math.cos(coordinateX1) * Math.cos(coordinateX2)
* Math.cos(coordinateY1 - coordinateY2);
System.out.println("distance1: "+distance1);
// 2 35.2270869 -80.8431267
double distance2 =
(earthRadius)
* Math.acos(Math.sin(coordinateX2) * Math.sin(coordinateX4))
+ Math.cos(coordinateX2) * Math.cos(coordinateX4)
* Math.cos(coordinateY2 - coordinateY4);
System.out.println("distance2: "+distance2);
// 3 28.5383355 -81.3792365
double distance3 = (earthRadius)
* Math.acos(Math.sin(coordinateX4) * Math.sin(coordinateX1))
+ Math.cos(coordinateX4) * Math.cos(coordinateX1)
* Math.cos(coordinateY4 - coordinateY1);
System.out.println("distance3: "+distance3);
// ******************************************************************************2
// 4 33.7489954 -84.3879824
// 1 35.2270869 -80.8431267
double distance01 = (earthRadius)
* Math.acos(Math.sin(coordinateX2) * Math.sin(coordinateX3))
+ Math.cos(coordinateX2) * Math.cos(coordinateX3)
* Math.cos(coordinateY2 - coordinateY3);
// System.out.println("distance: "+distance01);
// 2 32.0835407 -81.0998342
double distance02 = (earthRadius)
* Math.acos(Math.sin(coordinateX3) * Math.sin(coordinateX4))
+ Math.cos(coordinateX3) * Math.cos(coordinateX4)
* Math.cos(coordinateY3 - coordinateY4);
//System.out.println("distance: "+distance02);
// 3 28.5383355 -81.3792365
double distance03 =
(earthRadius)
* Math.acos(Math.sin(coordinateX4) * Math.sin(coordinateX2))
+ Math.cos(coordinateX4) * Math.cos(coordinateX2)
* Math.cos(coordinateY4 - coordinateY2);
// System.out.println("distance: "+distance03);
double rodistance1 = Math.ceil(distance1);
double rodistance2 = Math.ceil(distance1);
double rodistance3 = Math.ceil(distance3);
double rodistance01 = Math.ceil(distance01);
double rodistance02 = Math.ceil(distance02);
double rodistance03 = Math.ceil(distance03);
double s1 = (rodistance1 + rodistance2 + rodistance3) / 2;
double s2 = (rodistance01 + rodistance02 + rodistance03) / 2;
double area1 = Math.sqrt(s1 * (s1 - rodistance1) * (s1 - rodistance2)
* (s1 - rodistance3));
double area2 = Math.sqrt(s2 * (s2 - rodistance01) * (s2 - rodistance02)
* (s2 - rodistance03));
double totalArea = Math.ceil(area1 + area2);
System.out.println("The area is: " + totalArea);
}
}
//SAMPLE
//Please enter the coordinates in a clockwise order.
//Enter the GPS coordinates for the 1st city: 35.2270869 -80.8431267
//Enter the GPS coordinates for the 2nd city: 32.0835407 -81.0998342
//Enter the GPS coordinates for the 3rd city: 28.5383355 -81.3792365
//Enter the GPS coordinates for the 4th city: 33.7489954 -84.3879824
//The area is: 117863.342
I am getting 1.06664794E8 What can I do to get the answer as the sample? Unless I am having errors with my formulas, I should be getting a ok answer. I am using Math.ceil() it might not be what I really wanted I needed to round to 3 decimals .................................................................
Use BigDecimal and setScale()
BigDecimal bg1 = new BigDecimal("1.06664794E8");
// set scale of bg1 to 3 and using CEILING as rounding mode
bg1 = bg1.setScale(3, RoundingMode.CEILING);
System.out.println("After changing the scale to 3 and rounding is "+bg1);
Output:After changing the scale to 3 and rounding is 106664794.000
You can use BigDecimal here
double val = 1.06664794E8;
BigDecimal bigDecimal = new BigDecimal(val);
System.out.println(bigDecimal);
Out put:
106664794

Categories