cartesian slope calculation error Java - 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");
}

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

Making a fractal landscape look more realistic

In an STL format this is what my current landscape looks like. And this is what the landscape is suppossed to look like. I think I know what the problem is, but I have no clue how to solve it.
I think I need to set the Z coordinate relative to other points around it so the whole landscape's Z coordinate isn't between 0 and 1 but they rather "add up".
Don't want a solution, just a hint in the right direction.
import java.io.*;
import java.util.Random;
class Point3D {
double x, y, z;
Point3D(double dx, double dy, double dz) {
x = dx;
y = dy;
z = dz;
}
Point3D middlePoint(Point3D p) {
Point3D m = new Point3D(0.0, 0.0, 0.0);
m.x = (this.x + p.x) / 2.0;
m.y = (this.y + p.y) / 2.0;
m.z = (this.z + p.z) / 2.0;
return m;
}
}
public class Aufgabe3 {
public static void recursion(Point3D p1, Point3D p2, Point3D p3, int n) {
if (n > 0) {
if (n == 1) {
System.out.println(" facet normal 0.0 0.0 0.0");
System.out.println(" outer loop");
System.out.println(" vertex " + p1.x + " " + p1.y + " " + p1.z);
System.out.println(" vertex " + p2.x + " " + p2.y + " " + p2.z);
System.out.println(" vertex " + p3.x + " " + p3.y + " " + p3.z);
System.out.println(" endloop");
System.out.println(" endfacet");
}
Random r = new Random();
Point3D a = p1.middlePoint(p2);
Point3D b = p3.middlePoint(p1);
Point3D c = p2.middlePoint(p3);
long seedA = (long) ((p1.x + p1.y + p1.z + p2.x + p2.y + p2.z) * 1000000);
r.setSeed(seedA);
a.z = r.nextDouble() / 10;
long seedB = (long) ((p3.x + p3.y + p3.z + p1.x + p1.y + p1.z) * 1000000);
r.setSeed(seedB);
b.z = r.nextDouble() / 10;
long seedC = (long) ((p2.x + p2.y + p2.z + p3.x + p3.y + p3.z) * 1000000);
r.setSeed(seedC);
c.z = r.nextDouble() / 10;
recursion(p1, a, b, n-1);
recursion(a, p2, c, n-1);
recursion(b, c, p3, n-1);
recursion(a, b, c, n-1);
}
}
public static void main(String args[]) throws FileNotFoundException {
int n;
try {
n = Integer.parseInt(args[0]);
}
catch (Exception e) {
n = 7;
}
System.out.println("Aufgabe 3: Landschaftsgenerator");
System.out.println("n = " + n);
Random r = new Random();
Point3D p1 = new Point3D(0.8, -1.2, 0.0);
Point3D p2 = new Point3D(1.0, 1.3, 0.0);
Point3D p3 = new Point3D(-1.0, 0.0, 0.0);
System.setOut(new PrintStream(new FileOutputStream("Aufgabe3.stl")));
System.out.println("solid Aufgabe3");
recursion(p1, p2, p3, n);
System.out.println("endsolid");
}
}
The problem is the frequency distribution of the displacements you're adding. Displacements to a fractal landscape have to follow a 1/(f^b) distribution, otherwise you get random noise.
In this case, no matter what the scale of subdivision, you're adding the same vertical displacement, which is going to result in a landscape dominated by the highest frequency. Formally, a fractal surface is one that has a 'fractional' or 'fractal' geometric dimension, higher than the topological dimension of the surface, but lower than that of the embedding space. For instance, for a 2D surface being displaced in the 3rd dimension, the fractal dimension should be between 2 and 3.
For subdivision and displacement, the fractal dimension is related to beta as follows:
Dim = (7 - b)/2
With fractal behaviour therefore occurring between b = 1 and b = 3, and the random displacements follow this profile:
displacement = k * rand / (f^b)
This means that if you divide your triangle in half each time, you have to at least halve the displacement, or you'll end up with a noise surface rather than a fractal one. The best choice for a landscape is typically somewhere around b = 2.
Reference: https://fractal-landscapes.co.uk/maths.html

Forcing a square to fit in a grid

The method is supposed to draw a square on a 10x10 grid using the length and x,y coordinate an user inputs and adjust the length in case the square doesn't fit.
I'm having trouble figuring out the math for adjusting the length to fit the grid.
For example, if the user inputs (x-7, y-2, length-4) my square goes out of the grid by 1.
Example
public static void drawSquare(int x, int y, int len) {
if(x+len>10)
len = Math.max(x, len)-Math.min(x, len);
if(y+len>10)
len = Math.max(y, len)-Math.min(y, len);
System.out.println("side length = " + len + ", area = " + len*len);
drawLine(x, y, x+len, y);
drawLine(x+len,y,x+len,y-len);
drawLine(x+len, y-len, x, y-len);
drawLine(x, y-len, x, y);
}
This should do the trick. Just think about how the drawsquare method should call another method drawLine. Think about how to find each point in a square using the two coordinates and the given length of the square, also using if statements to make sure it fits the graph
public class unit3frq {
public void drawSquare(int x, int y, int len) {
// first check whether it fits on the grid
int xsum = x + len; int ydiff = y - len;
if (xsum > 10) xsum = 10 - x; if (ydiff < 0) ydiff = 0 - y;
if ((x - xsum) > (y - ydiff)) xsum = ydiff+x-y;
else ydiff = xsum+y-x;
drawLine(x, y, x, ydiff); // go down
drawLine(x, y, xsum, y); // go right
drawLine(x, ydiff, xsum, ydiff); // down then right
drawLine(xsum, y, xsum, ydiff); // right then down
int side = xsum - x;
System.out.println("side length = " + side + ", area = " + Math.pow(side, 2));
}
public void drawLine(int x1, int y1, int x2, int y2) {
int xdiff = x2 - x1; int ydiff = y2 - y1;
if (xdiff < 0) xdiff = 0 - xdiff; if (ydiff < 0) ydiff = 0 - ydiff;
if (xdiff > ydiff) {
int x = x1; int y = y1;
while (x <= x2) {
System.out.println("(" + x + ", " + y + ")");
x++;
if (ydiff != 0) y += ydiff / xdiff;
}
} else {
int x = x1; int y = y1;
while (y <= y2) {
System.out.println("(" + x + ", " + y + ")");
y++;
if (xdiff != 0) x += xdiff / ydiff;
}
}
}
public static void main(String[] args) {
unit3frq u3 = new unit3frq();
u3.drawSquare(0, 0, 10);
}
}

LIBGDX: How do I draw a filled polygon with the shaperenderer?

I have defined a shape using an array of vertices:
float[] points = new float[]{50,60,50,70,60,70, 60,60,50,60};
And I am drawing this here:
shapeRenderer.polygon(floatNew);
This just gives an outline of the shape.
How do I fill it with colour?
Thanks
Currently, ShapeRenderer supports polygon drawing (by line) but not filling.
This code is clipping the polygon on triangles, and then drawing each triangle separately.
Edit ShapeRenderer.java like this:
EarClippingTriangulator ear = new EarClippingTriangulator();
public void polygon(float[] vertices, int offset, int count)
{
if (shapeType != ShapeType.Filled && shapeType != ShapeType.Line)
throw new GdxRuntimeException("Must call begin(ShapeType.Filled) or begin(ShapeType.Line)");
if (count < 6)
throw new IllegalArgumentException("Polygons must contain at least 3 points.");
if (count % 2 != 0)
throw new IllegalArgumentException("Polygons must have an even number of vertices.");
check(shapeType, null, count);
final float firstX = vertices[0];
final float firstY = vertices[1];
if (shapeType == ShapeType.Line)
{
for (int i = offset, n = offset + count; i < n; i += 2)
{
final float x1 = vertices[i];
final float y1 = vertices[i + 1];
final float x2;
final float y2;
if (i + 2 >= count)
{
x2 = firstX;
y2 = firstY;
} else
{
x2 = vertices[i + 2];
y2 = vertices[i + 3];
}
renderer.color(color);
renderer.vertex(x1, y1, 0);
renderer.color(color);
renderer.vertex(x2, y2, 0);
}
} else
{
ShortArray arrRes = ear.computeTriangles(vertices);
for (int i = 0; i < arrRes.size - 2; i = i + 3)
{
float x1 = vertices[arrRes.get(i) * 2];
float y1 = vertices[(arrRes.get(i) * 2) + 1];
float x2 = vertices[(arrRes.get(i + 1)) * 2];
float y2 = vertices[(arrRes.get(i + 1) * 2) + 1];
float x3 = vertices[arrRes.get(i + 2) * 2];
float y3 = vertices[(arrRes.get(i + 2) * 2) + 1];
this.triangle(x1, y1, x2, y2, x3, y3);
}
}
}
You cant draw a filled Polygon with the shaperender yet. take a look at this from the bugtracker
You can also read that in the API.
public void polygon(float[] vertices)
Draws a polygon in the x/y plane. The vertices must contain at least 3
points (6 floats x,y). The ShapeRenderer.ShapeType passed to begin has
to be ShapeRenderer.ShapeType.Line.
API ShapeRender
Sure if its with ShapeType.Line you just get the outlines.
You need to draw it yourself with Triangles in that case. It should be possible to fill at least Triangles.
Maybe take a look at this from Stackoverflow: drawing-filled-polygon-with-libgdx
Edit your ShapeRenderer.java class replacing polygon() method with the following code:
public void polygon(float[] vertices, int offset, int count) {
if (currType != ShapeType.Filled && currType != ShapeType.Line)
throw new GdxRuntimeException(
"Must call begin(ShapeType.Filled) or begin(ShapeType.Line)");
if (count < 6)
throw new IllegalArgumentException(
"Polygons must contain at least 3 points.");
if (count % 2 != 0)
throw new IllegalArgumentException(
"Polygons must have an even number of vertices.");
checkDirty();
checkFlush(count);
final float firstX = vertices[0];
final float firstY = vertices[1];
if (currType == ShapeType.Line) {
for (int i = offset, n = offset + count; i < n; i += 2) {
final float x1 = vertices[i];
final float y1 = vertices[i + 1];
final float x2;
final float y2;
if (i + 2 >= count) {
x2 = firstX;
y2 = firstY;
} else {
x2 = vertices[i + 2];
y2 = vertices[i + 3];
}
renderer.color(color);
renderer.vertex(x1, y1, 0);
renderer.color(color);
renderer.vertex(x2, y2, 0);
}
} else {
for (int i = offset, n = offset + count; i < n; i += 4) {
final float x1 = vertices[i];
final float y1 = vertices[i + 1];
if (i + 2 >= count) {
break;
}
final float x2 = vertices[i + 2];
final float y2 = vertices[i + 3];
final float x3;
final float y3;
if (i + 4 >= count) {
x3 = firstX;
y3 = firstY;
} else {
x3 = vertices[i + 4];
y3 = vertices[i + 5];
}
renderer.color(color);
renderer.vertex(x1, y1, 0);
renderer.color(color);
renderer.vertex(x2, y2, 0);
renderer.color(color);
renderer.vertex(x3, y3, 0);
}
}
}
Usage:
gdx_shape_renderer.begin(ShapeType.Filled);
gdx_shape_renderer.setColor(fill_r, fill_g, fill_b, fill_a);
gdx_shape_renderer.polygon(vertices);
gdx_shape_renderer.end();
gdx_shape_renderer.begin(ShapeType.Line);
gdx_shape_renderer.setColor(border_r, border_g, border_b, border_a);
gdx_shape_renderer.polygon(vertices);
gdx_shape_renderer.end();

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