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.
Related
I'm trying to solve this problem.
Determine the distance between point (x1, y1) and point (x2, y2), and assign the result to pointsDistance.
I'll now present the original code along with my answer to the problem:
import java.util.Scanner;
public class CoordinateGeometry {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double x1;
double y1;
double x2;
double y2;
double pointsDistance;
double xDist;
double yDist;
pointsDistance = 0.0;
xDist = 0.0;
yDist = 0.0;
x1 = scnr.nextDouble();
y1 = scnr.nextDouble();
x2 = scnr.nextDouble();
y2 = scnr.nextDouble();
pointsDistance = Math.sqrt(x2 - Math.pow(x1, 2) + y2 - Math.pow(y1, 2)); //*Learning Square Rooots and powers*//
System.out.println(pointsDistance);
}
}
The desired outcomes from the inputs are not printing. For an example:
My value:
1
Expected value:
3
Where have I gone wrong?
Your formula is incorrect. It should be:
pointsDistance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
This is just an application of the Pythagorean theorem, and Java has a Math.hypot() convenience method that also protects against arithmetic overflow/underflow:
pointsDistance = Math.hypot(x2-x1, y2-y1);
Thanks to #LouisWasserman for the helpful comment.
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
}'
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.
This question already has answers here:
How to tackle a homework prgram that reads three sides for a triangle and computes the area if the input is valid?
(4 answers)
Closed 2 years ago.
This is a re-ask of the following question: How to tackle a homework prgram that reads three sides for a triangle and computes the area if the input is valid?
Here is the task again:
Create a class named MyTriangle that contains the following two methods:
/** Return true if the sum of any two sides is * greater than the third side. */
public static boolean isValid (double side1, double side2, double side3)
/** Return the area of the triangle. */
public static double area (double side1, double side2, double side3)
Write a test program that reads three sides for a triangle and computes the area if the input is valid. Otherwise, it displays that the input is invalid.
Attempt below: Question: I cannot figure this out and the constantly rereading the chapter isn't breaking through any walls. The issue is commented in the code below:
import java.util.Scanner;
public class NewClass1 {
double area;
double side1, side2, side3;
double x1, x2, x3, y1, y2, y3;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter two integers for side 1:");
double x1 = input.nextDouble();
double y1 = input.nextDouble();
System.out.print("Enter two integers for side 2:");
double x2 = input.nextDouble();
double y2 = input.nextDouble();
System.out.print("Enter two integers for side 3:");
double x3 = input.nextDouble();
double y3 = input.nextDouble();
boolean isValid = true;
if (isValid) {
System.out.println("Input is invalid");
}
else
area(side1, side2, side3); //Using area does not work and I don't know how to remedy this. I've read the chapter over and over... I cannot get it to work.
}
public static double area(double side1, double side2, double side3) {
double x1 = 0;
double x2 = 0;
double y1 = 0;
double y2 = 0;
double x3 = 0;
double y3 = 0;
side1 = Math.pow(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2), 0.5);
side2 = Math.pow(Math.pow(x3 - x1, 2) + Math.pow(y3 - y1, 2), 0.5);
side3 = Math.pow(Math.pow(x3 - x2, 2) + Math.pow(y3 - y2, 2), 0.5);
//Calculates the sides/angles using Heron's formula
double s = (side1 + side2 + side3)/2;
double area = Math.pow(s * (s - side1) * (s - side2) * (s - side3), 0.5);
return (area);
}
public static boolean isValid(double side1, double side2, double side3) {
return (((side1 + side2) > side3) && ((side1 + side3) > side2) && ((side2 + side3) > side1));
}
}
Reviewing the code, can someone please explain what it is that I'm doing wrong, and explain a possible remedy. Everything is there, I simply cannot connect the dots. Thank you.
Revised Code
import java.util.Scanner;
public class NewClass1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter side 1: ");
double side1 = input.nextDouble();
System.out.print("Enter side 2: ");
double side2 = input.nextDouble();
System.out.print("Enter side 3: ");
double side3 = input.nextDouble();
double a = area(side1, side2, side3);
boolean isV = isValid(side1, side2, side3);
if (isV)
System.out.println("Inout is Invalid");
else
System.out.println("Area is: " + a);
}
public static boolean isValid(double side1, double side2, double side3) {
return (((side1 + side2) > side3) && ((side1 + side3) > side2) && ((side2 + side3) > side1));
}
public static double area(double side1, double side2, double side3) {
//Calculates the sides/angles using Heron's formula
double s = (side1 + side2 + side3)/2;
double theArea = Math.pow(s * (s - side1) * (s - side2) * (s - side3), 0.5);
return (theArea);
}
}
I keep getting NaN as the answer for the area. What am I doing wrong?
I've been at this for over 7 hours simply because I don't understand the possible problems there are. I'm 2 months into this CompSci course.
Your method isValid returns true if the triangle is valid yet you're assuming the opposite:
double a = area(side1, side2, side3);
boolean isV = isValid(side1, side2, side3);
if (isV)
System.out.println("Inout is Invalid");
This is further supported by your input data (in a comment) of sides 11.1, 22.2 and 33.3. That's not a triangle, it's a series of overlapping line segments.
If you type in the perfectly valid 3/4/5 triangle, you'll get an error stating that it's not a triangle.
So, simply change the code above to be something like (there's no point calling area on invalid data):
if (! isValid(side1, side2, side3))
System.out.println("Inout is Invalid");
else
System.out.println("Area is " + area(side1, side2, side3));
Making those changes:
package test2;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter three sides, separated by spaces: ");
double s1 = input.nextDouble();
double s2 = input.nextDouble();
double s3 = input.nextDouble();
if (isValid(s1, s2, s3))
System.out.println("Area is: " + area(s1, s2, s3));
else
System.out.println("Input is Invalid");
}
public static boolean isValid(double s1, double s2, double s3) {
return ((s1 + s2 > s3) && (s1 + s3 > s2) && (s2 + s3 > s1));
}
public static double area(double s1, double s2, double s3) {
double s = (s1 + s2 + s3) / 2;
double theArea = Math.pow(s * (s - s1) * (s - s2) * (s - s3), 0.5);
return theArea;
}
}
and entering a valid triangle, like 3/4/5 or 5/5/8 gives you the correct results:
Enter three sides, separated by spaces: 3 4 5
Area is: 6.0
Enter three sides, separated by spaces: 5 5 8
Area is: 12.0
if (isV) should be if (!isV). If the condition isn't correct, then you're only executing Heron's formula with potentially dangerous input that can possibly cause s * (s - side1) * (s - side2) * (s - side3) to be negative. Taking the square root of a negative number is undefined with Java primitive types.
Use this .. Heron's formula
double sidesSvalue = (a + b + c)/2.0d;
double productofSides = (sidesSvalue * (sidesSvalue -a) * (sidesSvalue -b) * (sidesSvalue -c));
double Area= Math.sqrt(productofSides );
return Area;
whenever your values are invalid they are going into the area please correct your conditional code you should use something like this
if(!isValid)
print error message
else
calculate area
one last thing always try to use the same primitive type when using DMAS operations.
My job is to compute the following properties of a given triangle: lengths of all sides, angles at all corners, the perimeter and the area. I have a Triangle class and a Triangle tester class. I THINK I have coded the perimeter and area correctly? But I am beginning to think instead of setting a constant variable side for my perimeter I should be using the lengths of all sides to find my perimeter as well. What I am stuck on is finding the lengths and the angles. For some reason when I run my tester class they all come out as 1.0. Any advice would be appreciated! Thank you!
import java.util.Scanner;
public class Triangle
{
Scanner in = new Scanner(System.in);
/**
* Variables
*/
double x1;
double x2;
double x3;
double y1;
double y2;
double y3;
double lengthA;
double lengthB;
double lengthC;
double angleA;
double angleB;
double angleC;
double area;
double perimeter;
double base;
double height;
double p;
/**
Constructs x and y coordinates
#param x1, x2, x3 to x1, x2, x3
#param y1, y2, y3 to y1, y2, y3
*/
public Triangle(double x1, double x2, double x3, double y1, double y2, double y3)
{
this.x1 = x1;
this.x2 = x2;
this.x3 = x3;
this.y1 = y1;
this.y2 = y2;
this.y3 = y3;
}
/**
*Find lengths of all sides
*/
public double getLengthA()
{
lengthA = Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));
return lengthA;
}
public double getLengthB()
{
lengthB = Math.sqrt(Math.pow((x3 - x2), 2) + Math.pow((y3 - y2), 2));
return lengthB;
}
public double getLengthC()
{
lengthC = Math.sqrt(Math.pow((x1 - x3), 2) + Math.pow((y1 - y3), 2));
return lengthC;
}
/**
* Find angles at all corners
#return angles at all corners
*/
public double getAngleA()
{
angleA = lengthA + lengthB + lengthC - (lengthB * lengthC);
return angleA;
}
public double getAngleB()
{
angleB = lengthB + lengthA + lengthC - (lengthA * lengthC);
return angleB;
}
public double getAngleC()
{
angleC = lengthC + lengthA + lengthB - (lengthA * lengthB);
return angleC;
}
/**
* Constant Variables
*/
public Triangle()
{
base = 5;
height = 15;
}
/**
* Find perimeter of triangle
*/
public double getPerimeter()
{
perimeter = lengthA + lengthB + lengthC;
return perimeter;
}
public double getHalfPerimeter()
{
p = perimeter / 2;
return p;
}
/**
* Find area of triangle
*/
public double getArea()
{
double area = Math.sqrt(p * (p - lengthA) * (p - lengthB) * (p - lengthC));
return area;
}
}
Here is my tester class:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class TriangleSimulator
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
String input = JOptionPane.showInputDialog("Enter X coordinate for the first corner of the triangle: ");
double x1 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter Y coordinate for the first corner of the triangle: ");
double y1 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter X coordinate for the second corner of the triangle: ");
double x2 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter Y coordinate for the second corner of the triangle: ");
double y2 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter X coordinate for the third corner of the triangle: ");
double x3 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter Y coordinate for the third corner of the triangle: ");
double y3 = Double.parseDouble(input);
Triangle t = new Triangle(x1, x2, x3, y1, y2, y3);
System.out.println("Length A is: " + t.getLengthA());
System.out.println("Length B is: " + t.getLengthB());
System.out.println("Length C is: " + t.getLengthC());
System.out.println("Angle A is: " + t.getAngleA());
System.out.println("Angle B is: " + t.getAngleB());
System.out.println("Angle C is: " + t.getAngleC());
System.out.println("Area: " + t.getArea());
System.out.println("Perimeter: " + t.getPerimeter());
in.close();
}
}
You're showing JOptionPanes that prompt the user for input, but you're not getting the input and you're thus not using the input to set the state of your Triangle, creating a default Triangle object using its parameterless constructor. Understand that there's no magic in Java programming, and your Triangle object will not magically know what numbers the user has entered and change itself accordingly. Instead you must give that information into your Triangle.
What you must do is assign the results returned from the JOptionPanes, parse them into doubles, and then use those numbers to create a Triangle, using the constructor that takes numeric value parameters, not the default constructor. Do this, and you should be good.
e.g.
String input = JOptionPane.showInputDialog("Enter X coordinate for the first corner of the triangle: ");
double x1 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter Y coordinate for the first corner of the triangle:
double y1 = Double.parseDouble(input);
//.... etc repeat...
Triangle triangle = new Triangle(x1, x2, x3, y1, y2, y3);
Edit
This constructor ignores the values being passed in:
public Triangle(double x1, double x2, double x3, double y1, double y2, double y3)
{
x1 = 0;
x2 = 0;
x3 = 0;
y1 = 0;
y2 = 0;
y3 = 0;
}
A constructor like the one you'll need, should take the values passed in, and use those values to set class fields. For instance here:
public class Foo {
private int bar; // the bar field
public Foo(int bar) {
this.bar = bar;
}
}
Note that I use this.bar above so that Java knows that I want to set the bar field with the value held by the bar parameter (the bar without the this). You will need to do something similar only with 6 parameters, not one.
Then you do all your calculations in a separate block of code called an initializer block:
{
/**
* Find lengths of all sides
*/
lengthA = Math.pow(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2) * .05, lengthA);
lengthB = Math.pow(Math.pow((x3 - x2), 2) + Math.pow((y3 - y2), 2) * .05, lengthB);
lengthC = Math.pow(Math.pow((x1 - x3), 2) + Math.pow((y1 - y3), 2) * .05, lengthC);
}
This code gets called before your constructor, and so even if you set your Triangles fields correctly, this code wouldn't work. You don't want to use initializer blocks, and you can forget I even mentioned them other than to tell you not to use them. Instead do your calculations inside your constructor, and do so after setting all your fields.
Note that I've purposely not posted a solution to your problem because I firmly believe that what most of us need is to understand the concepts underlying any problems we are having, and then use that understanding to create our own code solutions.
Most important, read your texts, no better, study your texts, because the mistakes you're making involve foundational concepts, and show that you don't yet understand these concepts and have resorted to guessing. This will never work, as you need to understand all this and understand it well if you're going to be able to progress in this course.
Good luck!
Edit 2
For Tom, run this:
public class TestInitializerBlock {
public TestInitializerBlock() {
System.out.println("Inside of constructor");
}
{
System.out.println("Inside of initializer block");
}
public static void main(String[] args) {
new TestInitializerBlock();
}
}