I am new to Java. I know about some core basics of Java such as setter and getter and recently came across a getter with a parameter (not sure if it is correct way of calling it):
public double getDistance(Point p)
{
// what is inside here? Usually without the "Point p" I simply put "return distance;"
}
This method belongs to a class called Point and it is meant to get the calculation of distance from a private method in the same class.
I will appreciate if someone can enlighten me on the getter "parameter" and how I can apply the return in this method.
Thank you.
EDIT: Added the private calculation method
// Compute distance
private double distance(Point p)
{
double xx;
double yy;
double r;
xx = this.x - p.x;
yy = this.y - p.y;
r = Math.sqrt(nx * nx + ny * ny);
return r;
}
I think a simple argument rename will make things clear, you want to calculate the distance between two-points. Specifically, this point and that point. Assuming you have double x and y coordinates in each Point that might look like,
public double getDistance(Point that) {
double tmpX = that.x - this.x;
double tmpY = that.y - this.y;
return Math.sqrt((tmpX * tmpX) + (tmpY * tmpY));
}
Why not use Point2D? It has built-in methods for computing distances from a supplied point to some point you already have.
Point2D pt = new Point2D.Double(10,20);
double distance = pt.distance(new Point2D.Double(20,30));
System.out.println(distance);
Check it out at java.awt.geom.Point2D
Related
I'm trying to write a java program that will solve any ordinary differential equations using Euler method, but I don't know how to write a code to get any differential equation from the user. I was only able to write the code to solve a predefined ordinary differential equations.
I was able to come with a code to solve some particular ordinary differential equations which were written as functions in the program, I also made research online to look for similar problems but it seem they also wrote it to solve some designated problem not general questions on ordinary differential equations. This was found in most of the article have read online.
Here is my Euler class;
import java.lang.Math;
public class Euler {
private double x0, y0, x1, y1, h, actual;
public Euler (double initialx, double initialy,double stepsize,double finalx1) {
x0 = initialx; y0 = initialy; h=stepsize; x1 = finalx1;
}
public void setEuler (double initialx, double initialy,double stepsize,
double finalx1){
x0 = initialx;y0 = initialy;h =stepsize;x1 = finalx1;
}
public double getinitialx(){
return x0;
}
public double getinitialy(){
return y0;
}
public double getinitialexact(){
return (double) (0.9048*Math.exp(0.1*x0*x0));
}
double func(double x, double y){
return (double) (0.2*x*y);
}
double funct(double x){
return (double) (java.lang.Math.exp(0.1*x*x));
}
public double getinitialerror(){
return (double) Math.abs(actual - y0);
}
public double getEulerResult(){
for (double i = x0 + h; i < x1; i += h){
y0 = y0 + h *(func(x0,y0));
x0 += h;
double actual = (0.9048*funct(x0));
double error = Math.abs(actual - y0);
System.out.printf("%f\t%f\t%f\t%f\n",x0,y0,actual, error);
}
return y0;
}
}
Here is my Driver's class
import java.util.Scanner;
public class EulerTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Euler myEuler = new Euler(1.0,1.0,0.1,1.5);
System.out.println( "x\t explicit\tactual\t error\t " );
System.out.printf("%f\t%f\t%f\t%f\n", myEuler.getinitialx(),
myEuler.getinitialy(),myEuler.getinitialexact(),
myEuler.getinitialerror());
System.out.printf("my approximated value is %f\n\n",
myEuler.getEulerResult ());
System.out.println("enter another initial value of x: ");
double initialx = input.nextDouble();
System.out.println("enter another initial value of y: ");
double initialy = input.nextDouble();
System.out.println("enter another stepsize value of h: ");
double stepsize = input.nextDouble();
System.out.println("enter another upper bound of x: ");
double finalx1 = input.nextDouble();
myEuler.setEuler(initialx,initialy,stepsize,finalx1);
System.out.println( "x\t explicit\tactual\t error\t " );
System.out.printf("%f\t%f\t%f\t%f\n", myEuler.getinitialx(),
myEuler.getinitialy(),myEuler.getinitialexact(),
myEuler.getinitialerror());
System.out.printf("my approximated value is %f\n\n",
myEuler.getEulerResult ());
}
}
I will be glad if i can en lighted on how to write the java code to collect any ordinary differential equation from the user so as to solve using Euler's method.
What you are looking for is the ability to compile some code at run time, where part of the code is supplied by the user.
There is a package called JOOR that gives you a Reflect class that contains a compile method. The method takes two parameters (a package name:String and the Java code:String).
I've never personally used it, so can not vouch for its robustness, but here is a tutorial and the javadoc:
https://www.jooq.org/products/jOOR/javadoc/latest/org.jooq.joor/org/joor/Reflect.html#compile(java.lang.String,java.lang.String)
https://blog.jooq.org/2018/04/03/how-to-compile-a-class-at-runtime-with-java-8-and-9/
In your case, you would put your user supplied function in place of the following line of code:
return \"Hello World!\";\n"
Beware, you need to be 100% absolutely unconditionally guaranteed that the user can only ever enter a function to be solved. If they are supplying code, remember that unless you take safeguards, the code they enter could very easily be code the removes all of the files on your hard drive (or worse).
For the second part of your question - how do i implement a solution in Java using Euler's method, perhaps check out this link: Euler's Method in java or this https://rosettacode.org/wiki/Euler_method#Java which has it in pretty much every language you can imagine (and probably some you can't).
I'm using firebase (android) to store data and I'm saving users like below:
users{
abcdefghi{
name:"abc",
lat:"12.988",
long:-0.123,
desc:"all other desc"
},KLMNGHT{
name:"def",
lat:"11.988",
long:-1.123,
desc:" other desc"
}
}
I want to display all users who comes into my radius zone(proximity zone) which are defined by me according to my location . I am out of ideas . I looked upon Haversine formula. But i don't know to achieve that.
What is the best algorithm to find user?
private const double EARTH_RADIUS = 6378.137;
private static double rad(double d)
{
return d * Math.PI / 180.0;
}
public static double GetDistance(double lat1, double lng1, double lat2, double lng2)
{
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double a = radLat1 - radLat2;
double b = rad(lng1) - rad(lng2);
double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a/2),2) +
Math.Cos(radLat1)*Math.Cos(radLat2)*Math.Pow(Math.Sin(b/2),2)));
s = s * EARTH_RADIUS;
s = Math.Round(s * 10000) / 10000;
return s;
}
Maybe this code can help you.
So is the question strictly: given two points on earth A(lan1,lon1) B(lan2,lon2) find the distance between A and B? When you are saying 'best algorithm',do you mean best in terms of development time,time,memory?!
Anyways,assuming 'best' in terms of development time you could use:
1.Google's API explained here: https://developers.google.com/maps/documentation/distance-matrix/intro#DistanceMatrixRequests
2.Here is a simple implementation- but I haven't tested it myself yet-
https://www.geodatasource.com/developers/java
I am encountering a problem when creating a program to solve simple kinematics.
I run the program and find out the fields haven't been modified properly . Here is
the scrap of my program that initialise the object and setting the variables.
public class LinearConstantAcceleration1DKinematics {
private double distance;
private double speed;
private double acceleration;
private double time;
public LinearConstantAcceleration1DKinematics() {
/* initialize the object */
distance = 0;
speed = 0;
acceleration = 0;
time = 0;
}
public void setS(double s) {
this.distance = s;
}
//continue with 3 more setters which is created in the same way ,i have omitted them here
public double getU(){
double u_ans;
u_ans = (distance - 1/2 *acceleration*time*time )/time;
return u_ans;
}
}
And here is the main that uses the methods
LinearConstantAcceleration1DKinematics kinematics = new LinearConstantAcceleration1DKinematics();
kinematics.setS(175);
kinematics.setA(10);
kinematics.setT(5);
System.out.printf(%f\n", kinematics.getU());
The result is 35 which is incorrect.Many thanks for your help.
This has absolutely nothing to do with setter methods -- your division is wrong since 1 / 2 does int division and returns 0 resulting in the equation calculating simply distance / time.
Change to:
u_ans = (distance - 1.0 / 2.0 * acceleration * time * time) / time;
Lesson to learn: don't assume where the error is -- test it. Use a debugger or println statements to check the states of your variables as your program runs.
I need help with a lab. My teacher did not tell us anything and he told us to figure it out. So i can use any help I can get. Thank You
Step 1: Is everything good with step one including my distance formula and I am trying to set xx equal to x and yy equal to y so I have not clue how to do that could could you help me with that.
class Point {
private int x;
private int y;
public Point() // (0, 0)
{
x = 0;
y = 0;
}
public Point(int xx, int yy)
{
xx = x;
yy = y;
}
public int getX() // return field values
{
return x;
}
public int getY()
{
return y;
}
// Use the distance formula to find the distance of this point from the origin (0,0)
public double distanceFromOrigin()
{
int d = 0;
d = Math.squrt(Math.pow(xx - x) + (Math.pow(yy - y);
}
Is my distance formula good if not what is wrong and can you help me fix it.
Step 2: I need to find the manhattan distance
// Find the "manhattan" distance between current point and other.
// You can look at http://x...content-available-to-author-only...t.gov/dads//HTML/manhattanDistance.html for help
public double distance(Point other)
{/*write the code for here*/}
I really have no clue how to do step 2 so i can really use a lot of help thank you guys so much
Step 3: After i find the manhattan distance between current point and other. I need to change it to its new values which i have no clue how to get the new value and how to change it. After that i need to shift the point by the translation T which i have no clue how to do that so i need help on that
// Changes the coordinate to new values
public void setLocation(int x, int y)
{/*write the code for here*/}
//Shift the point by the translation T<x+h,y+k>
public void translate(int h, int k)
{/*write the code for here*/}
by the way guys I am just on the basic computer science so I can't use all the fancy stuff so keep it basic and simple
Like torvin said in the comments, that really looks like Java and not Javascript. Those are two different languages, despite the similar names.
Generally looking at your code, there are obvious mistakes, which make me wonder what IDE (integrated development environment) you are using to write code. A proper program that helps you write code will spot those.
Just in your distanceFromOrigin() you are missing:
2 closing bracets
Math.squrt() should be Math.sqrt()
You are not returning a value, despite having set the methods return type to double
You should probably first set up an IDE and do a basic Java tutorial before continuing, honestly.
Im studying for an upcoming exam and am working at sample problems, in particular the following one:
Add to class Point below an instance method called midpoint which returns an object of type Point representing the midpoint of two points, where one of the points is supplied as a parameter and the other is the current point (i.e. the point provided by the local instance variables). Note that midpoint returns a new Point object. Making good use of class Point, write a program which reads two points and prints their midpoint. The input consists of two lines where each line contains the x- and y-coordinates of a point. An example of input/output follows, with input indicated by bolding:
Enter two points
2.1 3.2
3.0 2.8
The midpoint is (2.55,3.0)
My code for the point class is as follows and seems to be ok (feel free to point out any errors or improvements):
class Point {
private double x, y; // coordinates
Point(double x0, double y0){ // all-args constructor
x = x0; y = y0;
}
Point(){}; // no-args constructor (defaults apply)
void get() {
x = Console.readDouble();
y = Console.readDouble();
}
public Point midPoint(Point p) {
double mx = (p.x + x)/2;
double my = (p.y + y)/2;
return new Point(mx,my);
}
public String toString()
{
return "(" + x + "," + y + ")";
}
}
And where I run into trouble is in actually using my midPoint method in the below code, any advice is appreciated.
import java.util.Scanner;
import java.io.*;
class Midpoint extends Point
{
public static void main (String[] args ) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter two points:");
double x1 = scanner.nextDouble();
double y1 = scanner.nextDouble();
double x2 = scanner.nextDouble();
double y2 = scanner.nextDouble();
Point p1 = new Point(x1, y1);
Point p2 = new Point(x2, y2);
p1.get();
return midPoint(p2);
}
}
The call to get() method seems unnecessary.
Secondly, call your midPoint using an object(as per the requirement in the question). Hence, it should be:
p1.midPoint(p2);
Finally, since that method returns a Point type, ensure you catch what is returned.
Point p3 = p1.midPoint(p2);
Well from what you've presented as your code , it's definitely wrong , midPoint is a class method so the only way to use it is to first instantiate the class , like you p1 , and then call the method for that specific instace:
Point p1 = new Point(whatever);
Point p2 = new Point(whatever);
Point p3 = p1.midPoint(p2);
your main method is void so it cant return point
if you want to operate on points p1 and p2, midpoint between them is p1.midPoint(p2) if you do this way, you don't need extend point class
what is your p1.get() actually doing? by any chance is it same as scanner?
Besides all that was written by others, your MidPoint class shouldn't extend Point class. I think you did that for purpose of using that midPoint method but it's wrong. You didn't add any new behaviour to Point class.
import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
int c=sc.nextInt();
int d=sc.nextInt();
System.out.println((a+c)/2,(b+d)/2);
}
}