I'm Suppoused to write a class with a constructor for a Point and a Line and in the Line class I'm suppoused to write a method that finds if two lines intersect or not. This is my Point class:
public class Point {
static double x;
static double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
This is my Line Class
public class Line {
public Line(Point x, Point y) {
}
// create two points for a line
static Point x1y1;
static Point x2y2;
// create another two points for another line
static Point x3y3;
static Point x4y4;
public static void main(String[] args) {
// create lines
Line line1 = new Line(x1y1, x2y2);
Line line2 = new Line(x3y3, x4y4);
//initialize points
x1y1 = new Point(1.0, 1.0);
x2y2 = new Point(3.0, 3.0);
x3y3 = new Point(1.0, 2.0);
x4y4 = new Point(4.0, 2.0);
//call method to find if lines intersect
findIntersection(line1, line2);
System.out.println(x1y1.x);
}
public static void findIntersection(Line line1, Line line2) {
double denominator = (x1y1.x - x2y2.x) * (x3y3.y - x4y4.y)
- (x1y1.y - x2y2.y) * (x3y3.x - x4y4.x);
double px = 0;
double py = 0;
if (denominator == 0) {
System.out.println("Lines are parallel, they do not intersect");
} else {
px = ((x1y1.x * x2y2.y - x1y1.y * x2y2.x) * (x3y3.x - x4y4.x) - (x1y1.x - x2y2.x)
* (x3y3.x * x4y4.y - x3y3.y * x4y4.x))
/ denominator;
py = ((x1y1.x * x2y2.y - x1y1.y * x2y2.x) * (x3y3.y - x4y4.y) - (x1y1.y - x2y2.y)
* (x3y3.x * x4y4.y - x3y3.y * x4y4.x))
/ denominator;
System.out.println(px + "," + py);
}
}
}
The problem is I initialize all the points so that the lines should intersect, but when I try to print out the values of the points, the values of the x-es and y-s of the firss 3 points are equal to the 4th one although I'm initializing them with different values and thus the method calcutes that the lines do not intersect. Why are the values of the first three y and x equal to the 4th?
It's because x and y of Point class are static. It means, every instance of Point class will use the same values. Remove static to fix it.
public class Point {
double x;
double y;
You should improve the class design too anyway: Two classes (Point, Lines) another with main method.
The same for Line too. Or you will end up with the same Points for every line. (You avoited this using 4 variables i think.)
Something like this
public class Point {
double x;
double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
public class Line {
Point a;
Point b;
public Line(Point a, Point b) {
this.a = a;
this.b = b;
}
public Point itIntersect(Line line) {
// here change the logic
Point point = null;
double denominator = (x1y1.x - x2y2.x) * (x3y3.y - x4y4.y)
- (x1y1.y - x2y2.y) * (x3y3.x - x4y4.x);
double px = 0;
double py = 0;
if (denominator != 0) {
px = ((x1y1.x * x2y2.y - x1y1.y * x2y2.x) * (x3y3.x - x4y4.x) - (x1y1.x - x2y2.x)
* (x3y3.x * x4y4.y - x3y3.y * x4y4.x))
/ denominator;
py = ((x1y1.x * x2y2.y - x1y1.y * x2y2.x) * (x3y3.y - x4y4.y) - (x1y1.y - x2y2.y)
* (x3y3.x * x4y4.y - x3y3.y * x4y4.x))
/ denominator;
// System.out.println(px + "," + py);
point = new Point(px, py);
}
return point;
}
}
P.S I didn't changed the logic of intersect because it's too long, but you could do something like this to improve the design.
Then you need to do Point point = line.itIntersect(anotherLine);
If it's null it don't intersect, else it will return the point.
P.S Make x and y private, i didn't because it was an example.
Related
I have a simple class 2Dpoints with two fields, x and y. I want to write a code so that I could command one point to moves slowly to another point, like so that it moves on the vector line of their distances. But I don't know how?
I've first thought that it should contain a for loop so that it would know, it should move till it reaches the other point
something like for(int d=0 ; d<distance ; d++) but I don't know how should I then command it so that it would move on the line?
import java.lang.Math.*;
public class Punkt {
private int x;
private int y;
public Punkt(int x, int y) {
this.x=x;
this.y=y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int distance) {
x = x + distance;
}
public void setY(int distance) {
y = y + distance;
}
public void moveAbout(int dx, int dy) {
x = x + dx;
y = y + dy;
}
/// method for calculating the distance to another point
public double giveDistance(Punkt otherPoint) {
return Math.sqrt(
(otherPoint.getY() - y) *
(otherPoint.getY() - y) +
(otherPoint.getX() - x) *
(otherPoint.getX() - x));
}
}
I've commented the major lines:
import static java.lang.Math.*;
/**
* Immutable structure. Functional way
*/
class Point {
public final double x;
public final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
/**
* Here you are. This is what you want to implement.
* from.moveTo(0.0, to) => from
* from.moveTo(1.0, to) => to
*
* #param by - from 0.0 to 1.0 (from 0% to 100%)
* #param target - move toward target by delta
*/
public Point moveTo(double by, Point target) {
Point delta = target.sub(this);
return add(delta.dot(by));
}
public Point add(Point point) {
return new Point(x + point.x, y + point.y);
}
public Point sub(Point point) {
return new Point(x - point.x, y - point.y);
}
public Point dot(double v) {
return new Point(v * x, v * y);
}
public double dist(Point point) {
return sub(point).len();
}
public double len() {
return sqrt(x * x + y * y);
}
public String toString() {
return x + ":" + y;
}
}
class Main {
public static void main(String[] args) {
Point source = new Point(2, 3);
Point target = new Point(-4, 9);
// You can utilize the cycle or implement kind of timer to animate something
for (int t = 0; t <= 100; t++) {
System.out.println(source.moveTo(0.01 * t, target));
}
}
}
https://replit.com/join/sucvdhpqoa-redneckz
#AlexanderAlexandrov I've change the type of my variables to double accordingly, now in one of my classes I have a method givePoints, which uses Scanner for asking a user how many points he wants and what are the coordinates then it saves them into an array of points with first element being always(0,0).
Another method takes an array of points as parameter and sort them in order of their distances to point(0,0).
These methods work perfectly. The problem is with method hitThepoints.
Here I want to first create the array of points, sort them, and then command my robot to hit all the points. robot is an object of class Robot extends circle, with position of type Point, that at first is at point(0,0)
public void hitThePoints(){
Point[] poi=sortPoints (givePoints()); //Creates a sorted array of points
Point short=new Point(poi[1].getX(),poi[1].getY());
System.out.println(" the nearest point is :");
System.out.println("("+short.getX()+ ","+short.getY()+")");
for(int i=1; i<poi.length;i++){
Point source=robot.position;
Point target=new Point(poi[i].getX(), poi[i].getY());
while(source.getX()!=target.getX() &&
source.getY()!=target.getY()){
robot.bewegeUm((source.moveTo(0.01,target)).getX(),
(source.moveTo(0.01,target)).getY());
if(source.getX()!=target.getX() &&
source.getY()!=target.getY()){break;}
System.out.println(source.getX() +","+ source.getY());
}
}
}
I am working on a desktop app that will help students with algebra. I have a class called Vector2 that just stores two variables, x and y. I am working on a method that will return the endpoint of a line given an endpoint and a midpoint. Just to show how I have been doing this here is a method
public static Vector2 midpoint(double xa, double ya, double xb, double yb){
Vector2 v = new Vector2(0, 0);
v.x = (xa + xb) / 2;
v.y = (ya + yb) / 2;
return v;
}
Given this how would I make a method that will give me the other endpoint?
Example: if the given endpoint is (-3, -5) and the given midpoint is (-6, -2) then the output should be (-9, 1)
EDIT FOR NEW PPL: I have the answer, it is pretty simple. Here is the final method
public static Vector2 otherEndpoint(double endPointX, double EndPointY, double midPointX, double midPointY){
Vector2 v = new Vector2(0,0);
v.x = (endPointX + midPointX) / 2;
v.y = (EndPointY + midPointY) / 2;
v.multiply(2);
return v;
}
v.multiply() is a method that I made that will multiply each point by whatever number you put in
public final class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public static Point getMidpoint(Point one, Point two) {
int x = (one.x + two.x) / 2;
int y = (one.y + two.y) / 2;
return new Point(x, y);
}
public static Point getEndpoint(Point one, Point mid) {
int x = (2 * mid.x) - one.x;
int y = (2 * mid.y) - one.y;
return new Point(x, y);
}
public static Vector2 fromEndAndMidpoint(double xa, double ya, double xmid, double ymid) {
Vector2 v = new Vector2();
v.x = 2 * xmid - xa;
v.y = 2 * ymid - ya;
return v;
}
Here is the method that shows how to compute it.
Note that this works because you know that one point is in the middle. So the desired endpoint is just one step away from the middle or two steps away from the other end.
public static Vector2 midpoint(double xe, double ye, double xm,
double ym) {
// calculate the step to go from the end point to the middle
// for both x and y.
double xstep = xm - xe;
double ystep = ym - ye;
// then just add the step to the middle to get the end point.
return new Vector2(xm + xstep, ym + ystep);
}
Note that the above will not work to find any point. For that you must simply find the equation of the line y = mx + b by computing the slope, m, and y-intercept, b.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Here is the error i'm getting:
airfoilNumber.java:5: error: cannot access airfoil
private airfoil myAirfoil = new airfoil();
^
bad class file: ./airfoil.class
class file contains wrong class: airfoil.airfoil
Please remove or make sure it appears in the correct subdirectory of the classpath.
Here is my main class:
import java.util.Scanner;
public class airfoilNumber
{
private airfoil myAirfoil = new airfoil();
public static void main(String[] args)
{
Scanner numNaca1 = new Scanner(System.in); //make a scanner and prompt user for their desired NACA number
System.out.println("What is your NACA number?"); //prompt user for NACA number
int numNaca = numNaca1.nextInt(); //apply the number to numNaca
new airfoil(numNaca); //call out airfoil class and run calculations
}
}
Here is my calculator class:
package airfoil;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class airfoil
{
private static final int numOfCoord = 250;
double dx = 1
.0 / numOfCoord;
private double m; // maximum camber in % of chord
private double p; // chordwise position of max ord., 10th of chord
private double t; // thickness in % of the cord
private String nacaNum; // NACA number - 4 digits
private double[][] coordinates; // Coordinates of the upper half or lower half of the airfoil
private double[][] meanLine; // mean line coordinates
public airfoil(String number) {
nacaNum = number;
m = Double.parseDouble(nacaNum.substring(0,1)) / 100.0;
p = Double.parseDouble(nacaNum.substring(1,2)) / 10.0;
t = Double.parseDouble(nacaNum.substring(2,4)) / 100.0;
meanLine = new double[2][numOfCoord]; // x values row 0, y values row 1
// x upper = row 0,
// y upper = row 1,
// x lower = row 2,
// y lower = row 3
coordinates = new double [4][numOfCoord];
System.out.println("NACA: " + nacaNum);
System.out.println("Number of coordinates: " + numOfCoord);
calcMeanLine();
calcAirfoil();
}
/*
* Calculates the values for the mean line forward of the maximum
* ordinate and aft of the maximum ordinate.
*/
private void calcMeanLine() {
double x = dx;
int j = 0;
// fwd of max ordinate
while (x <= p) {
meanLine[0][j] = x;
meanLine[1][j] = (m / (p * p))*(2*p*x - (x*x));
x += dx;
j++;
}
// aft of max ordinate
while (x <= 1.0 + dx) {
meanLine[0][j] = x;
meanLine[1][j] = (m / ((1 - p) * (1 - p))) *
((1 - 2*p) + 2*p*x - x * x);
x += dx;
j++;
}
} // end calcMeanLine
/*
* Calculate the upper and lower coordinates of the airfoil surface.
*/
private void calcAirfoil() {
double theta; // arctan(dy_dx)
double dy; // derivative of mean line equation
double yt, ml; // thickness and meanline values, respectively
double x = dx; // x-value w.r.t. chord
int j = 0; // counter for array
// calculate upper/lower surface coordinates fwd of max ordinate
while (x <= p) {
dy = (m / (p*p)) * (2*p - 2*x);
theta = Math.atan(dy);
yt = thicknessEQ(x);
ml = meanLine[1][j];
// upper surface coordinates;
coordinates[0][j] = x - yt * Math.sin(theta);
coordinates[1][j] = ml + yt * Math.cos(theta);
// lower surface coordinates
coordinates[2][j] = x + yt*Math.sin(theta);
coordinates[3][j] = ml - yt * Math.cos(theta);
x += dx;
j++;
}
// calculate the coordinates aft of max ordinate
while (x <= 1.0 + dx) {
dy = (m / ((1 - p) * (1 - p))) * ((2 * p) - (2 * x));
theta = Math.atan(dy);
yt = thicknessEQ(x);
ml = meanLine[1][j];
// upper surface coordinates;
coordinates[0][j] = x - yt * Math.sin(theta);
coordinates[1][j] = ml + yt * Math.cos(theta);
// lower surface coordinates
coordinates[2][j] = x + yt * Math.sin(theta);
coordinates[3][j] = ml - yt * Math.cos(theta);
x += dx;
j++;
}
System.out.println("j = " + j);
} // end calcAirfoil
/*
* Thickness equation
*/
private double thicknessEQ(double x) {
return ((t / 0.2) * (0.2969 * Math.sqrt(x) - (0.126 * x) -
(0.3526 * x * x) + (0.28430 * x * x * x) -
(0.1015 * x * x * x * x)));
}
public String toString() {
String str = "";
NumberFormat df = new DecimalFormat("0.0000");
System.out.println("Xu\tYu\tXl\tYl");
for (int j = 0; j < numOfCoord; j++) {
str += df.format(coordinates[0][j]) + "\t" +
df.format(coordinates[1][j]) + "\t" +
df.format(coordinates[2][j]) + "\t" +
df.format(coordinates[3][j]) + "\n";
}
return str;
}
/*
* Return the coordinates array
*/
public double[][] getCoordinates() { return coordinates; }
public int getSize() { return numOfCoord; }
} // end Airfoil class
Here is what i've tried:
Moving the airfoil.class file around from place to place to get it to work
use "new airfoil ("");" by itself, still gives me the same error
used any other type of code to call out my calculator class, same error.
I don't know what else to change. I don't know what it's telling me about "Wrong class airfoil.airfoil", that might be able to lead me to the solution.
What am i doing wrong here?
error is in:
new airfoil(numNaca); //call out airfoil class and run calculations
delete this line and call:
myAirfoil(numNaca);
new airfoil make new instance of youre class, not run calculations.
New instance exist in code, see line:
private airfoil myAirfoil = new airfoil();
and acces to this is myAirfoil.
You have the following class structure:
package airfoil;
public class airfoil {
...
}
public class airfoilNumber {
...
}
This needs to be reflected on the file system like this:
MyProject Project's top level directory
+-airfoilNumber.java
+-airfoil directory for "airfoil" package
+-airfoil.java
In addition, you then need to import airfoil.airfoil in your airfoilNumber class:
import airfoil.airfoil;
public class airfoilNumber {
}
With this setup, you can compile the two classes from within the project's top level directory with
C:> javac *.java
As a side comment, class names should start with uppercase letters. I kept the names from the question since casing mismatches between the class definition and its containing .java file can lead to other issues which are difficult to track, at least on MS Windows.
Once that is done, you need to fix the constructors of your airfoil class. There is currently only one constructor which takes a String argument, but you call it as follows:
private airfoil myAirfoil = new airfoil();
// does not compile - no non-arg constructor available
...
new airfoil(numNaca);
// does not compile - numNaca is int, constructor expects String
I have a method that gets the area of a triangle, however it is returning 0.0.
public double getArea() {
//Find the length of sides
double side1 = p1.findLength(p2);
double side2 = p2.findLength(p3);
double side3 = p3.findLength(p1);
//Get area
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
My Point class with findLength(). This function works as intended in my testing:
public double findLength(Point another) {
return Math.sqrt(((another.getX() - this.getX()) * (another.getX() - this.getX()) )+
((another.getY() - this.getY()) * (another.getY() - this.getY())));
}
I can't seem to figure out why it isn't working.
Entire Point class:
/**
* Created by wilson on 9/8/2014.
*/
import java.math.*;
public class Point {
private double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double findLength(Point another) {
return Math.sqrt(((another.getX() - this.getX()) * (another.getX() - this.getX()) )+
((another.getY() - this.getY()) * (another.getY() - this.getY())));
}
}
My Test Program:
Point p1 = new Point(0,0);
Point p2 = new Point(3,3);
Point p3 = new Point(-3,-3);
Triangle2D t1 = new Triangle2D(p1, p2, p3);
System.out.println("Area of triangle: " + t1.getArea());
The "triangle" you tested:
Point p1 = new Point(0,0);
Point p2 = new Point(3,3);
Point p3 = new Point(-3,-3);
actually consists of three points all on the same line (the line x = y). Therefore, 0 is the correct answer. As far as I can tell, the code is correct.
Side note: I recommend using Math.hypot, which computes sqrt(x2 + y2) in the findLength function. Besides making findLength easier to read, it has the advantage that it won't overflow if x or y is so large that x2 or y2 won't fit in a floating-point number. (Not that it's likely you'll run into that problem, but why not do things right?)
The Mandelbrot set has been a favorite of mine for many years. I've successfully created it in Pascal years ago and more recently on a TI-83 graphing calculator (Java renders it juuuuust a bit faster).
Since complex numbers are involved, I took a version from a text that extends RecursiveAction using a BufferedImage and ForkJoinPool (without understanding the those concepts and the overall implementation) and, using routines I developed a few months ago, modified (the heck out of) the code that does the point-plotting so that it looks more like complex numbers are involved.
Original:
public class MandelbrotTask extends RecursiveAction {
...
public void render() {
...
for (int x = xStart; x <= xEnd; x++) {
for (int y = yStart; y <= yEnd; y++) {
double r = x * zoomFactor / image.getWidth() - zoomFactor / 2 + offsetX;
double i = y * zoomFactor / image.getHeight() - zoomFactor / 2 + offsetY;
double zr = 0, zi = 0;
int iter;
for (iter = 0; iter < maxIter; iter++) {
double nzr = zr * zr - zi * zi + r;
double nzi = 2 * zr * zi + i;
if (nzr * nzr + nzi * nzi > escapeRadius * escapeRadius)
break;
zr = nzr;
zi = nzi;
}
image.setRGB(x, y, Color.HSBtoRGB(0.5f * iter / maxIter, 1.0f, 1.0f));
}
}
My revised, somewhat-cleaner code:
for (int x = xStart; x <= xEnd; x++) {
for (int y = yStart; y <= yEnd; y++) {
z1 = new ComplexNumber(x * dx - zoomFactor / 2 + offsetX,
y * dy - zoomFactor / 2 + offsetY);
z0 = new ComplexNumber(0,0);
int iter;
for (iter = 0; iter < maxIter; iter++) {
nz = cAdd(cMult(z0,z0),z1);
if (cAbs(nz) > escapeRadius )
break;
z0 = nz;
}
image.setRGB(x, y, Color.HSBtoRGB(0.5f * iter / maxIter, 1.0f, 1.0f));
}
}
My only question is how to get rid of "new" on the two lines defining z1 and z0. It seems like I'm wasting a ton of memory since the two objects get "newed" a total of 1,000,000+ times during the almost 25,000 executions of the above block of code, though there's no problem as is.
I know I need new at least once inside the method, but if I put the statements (shown below) outside the loop (and either inside or outside render()), if I omit new from those two lines defining z1 and z0 in the block of code above, I get the error
"cannot find symbol: method ComplexNumber(double,double) location: class MandelbrotTask."
z1 = new ComplexNumber();
z0 = new ComplexNumber();
---- edit 10:21 12/26/13
Here is the part of the ComplexNumber class that is invovled. The constructor call ComplexNumber() sets real and imag-inary parts to 0.
class ComplexNumber {
public double real;
public double imag;
public ComplexNumber() {
real = 0.0;
imag = 0.0;
}
public ComplexNumber(double r, double i) {
this.real = r;
this.imag = i;
}
public static ComplexNumber cAdd(ComplexNumber a, ComplexNumber b) {
return new ComplexNumber(a.real + b.real, a.imag + b.imag);
}
public static ComplexNumber cMult(ComplexNumber a, ComplexNumber b) {
return new ComplexNumber(a.real * b.real - a.imag * b.imag, a.real * b.imag + a.imag * b.real);
}
public static double sqr(double x) {
return x * x;
}
public static double cAbs(ComplexNumber z) {
return Math.sqrt(sqr(z.real) + sqr(z.imag));
}
}
Got a few upvotes, so I am converting my comment to an answer. If you want to avoid reinstantiating over and over again inside the loop, your only way out is to create setter methods for your ComplexNumber class:
public void setReal(double real) { this.real = real; }
public void setImaginary(double im) { this.im = im; }
public void setTo(double real, double im) { setReal(real); setImaginary(im); }
I am assuming your class has fields called real and im.
Moreover, if you can't modify the class itself, you should extend it by creating a wrapper class of the form class MyComplexNumber extends ComplexNumber, and then implement the setter methods for MyComplexNumber.
Types are good but I don't see a need for them here if your problem is memory.
Try creating methods inside ComplexNumber such as
public void init(){
//clear and reset all variables inside ComplexNumber
...
}
and
public void set(param1, param2...){
//set required variables
...
}
Then use set() and init() respectively inside your loop instead of creating a new instance each time. This works if you don't need references to the objects created inside the loop.
I should have pointed out in advance that the following code--with no new, no setters--accomplishes the task:
z1.real = x * dx - zoomFactor / 2 + offsetX;
z1.imag = y * dy - zoomFactor / 2 + offsetY;
z0.real = 0;
z0.imag = 0;
I was just hoping for something along the lines of my original revised code, one line per complex number.
====================
Here's me extending ComplexNumber class into a RealNumber class (which seems a bit backward, but...):
class RealNumber extends ComplexNumber
{ // RealNumber IS-A subclass ...
RealNumber() {}
RealNumber(double r) {
super.imag = 0; // ... THIS kind of subclass ...
super.real = r; // ... of ComplexNumber!
}
}
============================
Hey, #Chthonic, this worked:
public void setReal(double real) { this.real = real; }
public void setImaginary(double imag) { this.imag = imag; }
public void makeComplex(double real, double imag) { setReal(real); setImaginary(imag); }
...
z1 = new ComplexNumber();
z0 = new ComplexNumber(); // before loop
...
z1.makeComplex(x * dx - zoomFactor / 2 + offsetX,y * dy - zoomFactor / 2 + offsetY);
z0.makeComplex(0, 0);
THANKS for the idea. I'm not certain I got exactly why my original z1 = new Complex... didn't work, but I'll think about the replies.
(I just realized that I "learned" something that I already "knew". Happens all the time.)