Everything I do is either over-complicated or wrong - java

// *************************************************************
// Distance.java
// Computes the distance between two points in java
// *************************************************************
import java.util.Scanner;
import java.lang.Math;
public class Distance
{
public static void main (String[] args)
{
double x1, y1, x2, y2; // coordinates of two points
double distance; // distance between the points
//Formula - D=√(x2-x1)^2 + (y2-y1)^2
Scanner scan = new Scanner(System.in);
// Read in the two points
System.out.print ("Enter the coordinates of the first point " +
"(put a space between them): ");
x1 = scan.nextDouble();
y1 = scan.nextDouble();
System.out.print ("Enter the coordinates of the second point: ");
x2 = scan.nextDouble();
y2 = scan.nextDouble();
// Compute the distance
double math = x1-x2 * y1-y2;
// Print out the answer
System.out.print("The distance between (" + x1 + "," + x2 + ") and (" + y1 + "," + y2 + ") is") ;
}
}
I keep running into errors and I go on forever with codes that can be done faster and shorter. All I need to do is read the user input for coordinates, find the distance between them, and print the answer.

First you create your Point Class. Remember this is Java and OOP
class Point {
private double x;
private double y;
private String name;
public Point(String n, double xx, double yy) {
this.name = n;
this.x = xx;
this.y = yy;
}
public double getX() {
return this.x;
}
public double getY() {
return this.y;
}
public String getName() {
return this.name;
}
}
Secondly you create your Distance class with the distance calculating method
public double getEuclideanDistance(Point p, Point q) {
double ed = Math.sqrt((q.getX() - p.getX()) * (q.getX() - p.getX()) + (q.getY() - p.getY()) * (q.getY() - p.getY()));
return ed;
}
Lastly modify you main method as below
public static void main(String[] args) {
double Xp;
double Yp;
double Xq;
double Yq;
Scanner reader = new Scanner(System.in);
System.out.print("Enter x- cordinate of P : ");
Xp = reader.nextDouble();
System.out.print("Enter y- cordinate of P : ");
Yp = reader.nextDouble();
System.out.print("Enter x- cordinate of Q : ");
Xq = reader.nextDouble();
System.out.print("Enter y- cordinate of Q : ");
Yq = reader.nextDouble();
Point q = new Point("Q", Xq, Yq);
Point p = new Point("P", Xp, Yp);
System.out.println("Point " + p.getName() + "'s Coordinates are: " + "P(" + p.getX() + " , " + p.getY() + ")");
System.out.println("Point " + q.getName() + "'s Coordinates are: " + "Q(" + q.getX() + " , " + q.getY() + ")");
System.out.println("The Euclidean distance from p to q is :" + getEuclideanDistance(p, q));
}

The issue is that you are not quite implementing the distance formula the correct way... you have double math = x1-x2 * y1-y2 but aren't calling Math.pow() or Math.sqrt() at all.
Try to implement the following:

Related

equation firs degree in java implementing OOP

I want to translate a java code. I did in only one class but I want to implement OOP using two classes
The original code is working in only one class
However, when I created two classes equationMain and equationData, I get an error in the metod getter
public double calculateSlope() when I try to return the value of m(slope)
"Change method type to String"
I don't understand because I want to retuns a double value?
I will appreciate any help with this code
Original code in only one class:
package equation;
import javax.swing.JOptionPane;
public class Equation {
public static void main(String[] args) {
// TODO Auto-generated method stub
//variables for coordenates, slope, etc.
double x1, x2, y1, y2, m, b;
String firstcoordinate = JOptionPane.showInputDialog("Introduce coordinate 1 x1,y1 split by ,: ");
String[] values = firstcoordinate.split(",");
x1 = Double.parseDouble(values[0]);
y1 = Double.parseDouble(values[1]);
String secondcoordinate = JOptionPane.showInputDialog("Introduce coordinate 2 x2,y2 split by ,: ");
values = secondcoordinate.split(",");
x2 = Double.parseDouble(values[0]);
y2 = Double.parseDouble(values[1]);
if ((x1 == x2) || ((x2 - x1) == 0))
{
System.out.println("There is not equation!!");
}
else
{
m = (y2 - y1) / (x2 - x1);
//y1-mx1=b
b = (y1 - (m * x1));
System.out.println("Coordinates entered: ");
System.out.println(" *-Coordinate 1: (" + x1 + ", " + y1 + ")");
System.out.println(" *-Coordinate 2: (" + x2 + ", " + y2 + ")");
System.out.println("The slope m is = " + m );
System.out.println("The equation is y = " + m + "x + " + b);
}
}
}
However, my new project is:
//main class equationMain
package equationPOO;
import javax.swing.JOptionPane;
public class equationMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
//variables for coordenates, slope, etc.
double x1, x2, y1, y2, m, b;
String firstcoordinate = JOptionPane.showInputDialog("Introduce coordinate 1 x1,y1 split by ,: ");
String[] values = firstcoordinate.split(",");
x1 = Double.parseDouble(values[0]);
y1 = Double.parseDouble(values[1]);
String secondcoordinate = JOptionPane.showInputDialog("Introduce coordinate 2 x2,y2 split by ,: ");
values = secondcoordinate.split(",");
x2 = Double.parseDouble(values[0]);
y2 = Double.parseDouble(values[1]);
equationData eq = new equationData(x1,x2,y1,y2);
if((x1 == x2) || ((x2 - x1) == 0))
{
eq.message();
}
else
{
eq.calculateSlope();
}
}
}
Mys econd class where I want to follow the procedure is
package equationPOO;
public class equationData {
//constructor
public equationData(double x1, double x2, double y1, double y2)
{
this.x1= x1;
this.x2= x2;
this.y1= y1;
this.y2= y2;
}
//getter for calculating slope m
public double calculateSlope()
{
double m,b;
m = (y2 - y1) / (x2 - x1);
//y1-mx1=b
b = (y1 - (m * x1));
System.out.println("Coordinates entered: ");
System.out.println(" *-Coordinate 1: (" + x1 + ", " + y1 + ")");
System.out.println(" *-Coordinate 2: (" + x2 + ", " + y2 + ")");
System.out.println("The slope m is = " + m );
System.out.println("The equation is y = " + m + "x + " + b);
return "The slope m is = " + m;
}
//getter send a message is ((x1 == x2) || ((x2 - x1) == 0))
public String message()
{
return "There is not equation!!";
}
private double x1,x2,y1,y2;
}

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
}'

Calculating the distance between 2 given points

I have to create a class to calculate the distance between 2 given points for class. The instructor gave us the top half of the assignment with all the necessary code without modifying, the problem that im having is creating the class part. This is what i have so far...
class Point{
int x;
int y;
public Point(){
this.x = 0;
this.y = 0;
}
public Point(int x, int y){
this.x = x;
this.y = y;
}
public double distance(int x, int y) {
double d = Math.sqrt( Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2) );
return distance;
}
}
the top half of the assignment looks like this:
import java.util.Scanner;
class Assignment4{
public static void main(String[] args){
// first and second points
Point first, second;
// try parsing points from command line args
if(args.length==4){
// new Point(int x, int y) creates a new Point located at position (x,y)
first = new Point(Integer.valueOf(args[0]), Integer.valueOf(args[1]));
second = new Point(Integer.valueOf(args[2]), Integer.valueOf(args[3]));
}
// if not specified as argument, get points from user
else{
Scanner input = new Scanner(System.in);
System.out.println("Enter first point: ");
first = new Point(input.nextInt(),input.nextInt());
System.out.println("Enter second point: ");
second = new Point(input.nextInt(),input.nextInt());
}
//calculate distance
//double d = Math.sqrt( Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2) );
double d = first.distance(second.x, second.y);
System.out.println("Distance between " +
"(" + first.x + "," + first.y + ")" +
" and " +
"(" + second.x + "," + second.y + ")" +
" is " + d);
System.out.println();
}
}
When i try and compile the program, it says "cannot find symbol" referring to x2, x1, y2, y1, and distance.
Here :
class Point{
int x;
int y;
.....
.....
public double distance(int x, int y) {
double d = Math.sqrt( Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2) ); //ERROR IN THIS LINE
return distance; //ERROR HERE TOO...(2)
}
}
There is no x1,x2,y1,y2 defined in the class or in the method parameter.
Swap it with the following line:
double d = Math.sqrt( Math.pow(this.x-x, 2) + Math.pow(this.y-y, 2) );
(2)
Error 2 Swap with this line:
return d;

cartesian slope calculation error Java

I'm having some trouble with the my cartesian slope calculations in Java.
So my sourcecode lets you input 4 numbers, x1 y1 x2 y2, which represent 2 coordinates of 2 points in an cartesian coordinate system.
then i calculate the slope by calculating deltaX and deltaY.
so i use a double for the slope end calculation (deltaY / deltaX) in case you get a tenth of a number.
then i use an IF function to say: if slope = 0 --> println("not a linear line"). else calculate the cross point of the X and Y polars and println the result
So here is the problem: what if the slope is 0 (example x1:0 y1:1 x2:0 y2:9) then the i get an error: Exception in thread main java.lang.ArithmeticException: / by zero
here is the full script:
import java.io.*;
public class Cartesian
{
public static int leesIn(String var, BufferedReader in) throws IOException
{
System.out.println("type een getal in die " + var + " moet voorstellen.");
return Integer.parseInt(in.readLine());
}
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int x1, x2, y1, y2;
x1 = leesIn("X1", in);
y1 = leesIn("Y1", in);
x2 = leesIn("X2", in);
y2 = leesIn("Y2", in);
System.out.println("The Coördinates of point 1 is: (" + x1 + ", " + y1 + "). The Coördinates of point 2 is: (" + x2 + ", " + y2 + ").");
int deltaY = y2 - y1;
int deltaX = x2 - x1;
double RC = deltaY / deltaX;
if ((RC) == 0)
{
System.out.println("The slope is 0, no linear line.");
}else
{
System.out.println("The slope is: " + RC);
double B = y1-(RC*x1);
System.out.println("The crosspoint with Y, if x is 0, : " + B);
}
}
}
anyone an idea how to fix my problem? tnx in advance!
You should move calculation into area where you are sure that it can be calculated (in your case double RC = deltaY / deltaX;
So your code will be:
int deltaY = y2 - y1;
int deltaX = x2 - x1;
if (deltaY == 0)
{
System.out.println("The slope is 0, no linear line.");
}else if (deltaX == 0)
{
System.out.println("Not a Linear Line");
}else
{
double RC = (double) deltaY / deltaX;
System.out.println("The slope is: " + RC);
double B = y1-(RC*x1);
System.out.println("The crosspoint with Y, if x is 0, : " + B);
}
Make a try catch block
double RC;
try{
RC = deltaY / deltaX;
}
catch(ArithmeticException ex){
System.out.println("Not a Linear Line");
}
try this
try {
double RC = deltaY / deltaX;
if ((RC) == 0)
{
System.out.println("The slope is 0, no linear line.");
}else
{
System.out.println("The slope is: " + RC);
double B = y1-(RC*x1);
System.out.println("The crosspoint with Y, if x is 0, : " + B);
}
} catch(ArithmeticException ae) {
System.out.println("Not a linear line");
}

How to detect overlapping circles and fill color accordingly?

I created 5 circles with random x and y coordinates and radii using 3 arrays (for x, y and radius size). However, I need the circles to dynamically change color based on whether or not they overlap with another circle. So if one of the 5 circles doesn't overlap at all, it should be colored black. Overlapping circles should be cyan. Two circles are considered to overlap if the distance between their center points is less than the sum of their radii.
This is what I have written so far for the circles class.
The following code will successfully draw the 5 circles in an applet window, and the distances are successfully calculated, but the problem is with the coloring. There's seems to be a logic error in the color filling and I don't see the problem here. Any suggestions? Thank you so much.
public class Circles extends Applet {
public void paint(Graphics page)
{
Random locator = new Random();
int [] xpt = new int [5];
int [] ypt = new int [5];
int [] rad = new int [5];
setPreferredSize (new Dimension(300, 300));
for (int i = 0; i < xpt.length; i++){
xpt[i] = locator.nextInt(100); //need to set a number or it goes into millions, cannot set it in Random()
ypt[i] = locator.nextInt(100);
rad[i] = locator.nextInt(100);
System.out.println("The #" + i + " x-point: " + xpt[i] + " y-point: " + ypt[i] + " radius: " + rad[i]); //for debugging purposes
for (int j = 0; j < xpt.length; j++){
double xpoint1 = xpt[i]+rad[i];
double ypoint1 = ypt[i]+rad[i];
double xpoint2 = xpt[j]+rad[j];
double ypoint2 = ypt[j]+rad[j];
double radius1 = rad[i];
double radius2 = rad[j];
double theDistance = distance(xpoint1,ypoint1,xpoint2,ypoint2);
System.out.println("Comparing " + i + " to " + j); //for debugging and logic checking
if (i==j)
;
else if (theDistance <= (radius1+radius2))
{
page.setColor(Color.cyan);
page.fillOval(xpt[i], ypt[i], rad[i], rad[i]);
//page.fillOval(xpt[j], ypt[j], rad[j], rad[j]);
System.out.println("Overlap occurred. Colored " + i + " and " + j + " cyan.");
System.out.println("Center points: ("+ xpoint1 +", "+ ypoint1 +") and ("+ xpoint2 + ", "+ ypoint2 + ").");
}
else
{
page.setColor(Color.black);
page.fillOval(xpt[i], ypt[i], rad[i], rad[i]);
//page.fillOval(xpt[j], ypt[j], rad[j], rad[j]);
System.out.println("No overlap. Made " + i + " and " + j + " black.");
}
}
}
}
public static double distance(
double x1, double y1, double x2, double y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
}
The xpoint, ypoint, etc. lines are not doing what you think.
If you want to find if two circles are overlapping, you need to find if the distance between the centers of the circles is greater or less than the sum of their radii.
So:
function circlesCollide(x1, y1, r1, x2, y2, r2){
return (distance(x1, y1, x2, y2) <= (r1 + r2));
}
Why do you +rad[] here? You don't have to add the radius for comparing the distance.
double xpoint1 = xpt[i]+rad[i];
double ypoint1 = ypt[i]+rad[i];
double xpoint2 = xpt[j]+rad[j];
double ypoint2 = ypt[j]+rad[j];
[...]
double theDistance = distance(xpoint1,ypoint1,xpoint2,ypoint2);
[...]
page.fillOval(xpt[i], ypt[i], rad[i], rad[i]);
You should use xpt / ypt for the distance. not xpoint1, and use - for value and 2 * radius for size ...... i.e.:
double xpoint1 = xpt[i]-rad[i];
double ypoint1 = ypt[i]-rad[i];
double xpoint2 = xpt[j]-rad[j];
double ypoint2 = ypt[j]-rad[j];
[...]
double theDistance = distance(xpt[i],ypt[i],xpt[j],ypt[j]);
[...]
page.fillOval(xpoint1 , ypoint1, 2*rad[i], 2*rad[i]);

Categories