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);
}
}
Related
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
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 have a variable private Point _centralStation which located in class that I called her City.
the user in the main class decides which value will be to the location of the centralStation.
So he put for example:
Point center = new Point(5,5) .
I want to create a method who called MoveCentralStation(int x, int y)
that moves the location from his last value to the new one, but
the new points have to be in the first quarter of the x,y axis.
I mean x cannot be -4 for example.
let's say for the exmaple it was 5,5
and now the user entered -4,5
how can I deal with the x and y new values sepertely?
Thank you
You have to explain yourself a little better. However, this is what I understood.
You have such a class:
class City{
private Point _centralStation;
public City(){
this._centralStation = new Point(5,5);
//the initialization you specified
}
public void moveCentralStation(int new_x, int new_y){
//TODO exactly what you have to implement
}
public Point getCentralStation(){
//since you are not implementing just getters and setters you rather do
return new Point(_centralStation.x,_centralStation.y);
//instead of return _centralStation [this is what we call defensive copies]
}
}
Well, somewhere in the code, a client would call
City c = new City();
c.moveCentralStation(x,y); //given x,y are variables in the client's context
And these are the requirements for the moveCentralStation(int x, int y) operation:
x coordinate shall be positive
y coordinate shall be positive
First of all I suggest you to follow style conventions on the way you code: use capital letters only for the class names. Let's jump into the real problem.
We need to refine the above requirements to make a specific implementation compliant with them. They aren't clear enough. An example of refinining i may suggest is the following:
If x coordinate is less than zero, an IllegalArgumentException shall be thrown
If y coordinate is less than zero, an IllegalArgumentException shall be thrown
And that's very simple to implement:
public void moveCentralStation(int new_x, int new_y){
if(new_x < 0) throw new IllegalArgumentException("x must be positive");
if(new_y < 0) throw new IllegalArgumentException("y must be positive");
_centralStation.x = new_x;
_centralStation.y = new_y;
}
It's a good practice to set private fields only when they are all consistants.
Is there an efficient algorithm to find straight lines from an unsorted collection of x/y coordinates?
It would be ideal if:
a line is only recognized if at least n (more than two) points are aligned.
It allows a tolerance, so for example the following three coordinates would be considered a (horizontal) line: 10/100, 20/99, 30/100.
Is there some kind of standard approach to solve this? Maybe any (java) libraries? How would you solve it?
I would suggest using two maps, one for horizontal lines and one for vertical ones.
for every point, the key is the X or Y coordinate and the value is the point (use a list of points as values). Now go over the maps, and for each key show the points if there are more than one point, for each key, you should also count the points in the next keys (like in the case of 99 and 100).
I'm not sure if there'd be an efficient algorithm unless you already know of some relationship between the points.
The algorithm I outline below I guess would run in n^4 time.
You'd have something like
public class Line
{
static float tolerance;
float m, cLower, cUpper;
ArrayList<Point> onThisLine = new ArrayList<Point>();
public Line(double m, double c)
{
this.m = m;
cLower = c-tolerance;
cUpper = c+tolerance;
}
public boolean fitsInLine(Point xy)
{...}
public void addToList(Point xy)
{...}
}
where m and c represent what we learned in high school as the gradient and constant of the straight line.
For each point you'd have to compare it to every other point, generate a Line object, and then compare the new Line object to every existing Line and if it doesn't already exist then add it. Note that due to the slight tolerance you allow you consequentially have to allow for a similarity between Lines.
For example, y=-x/10+101 and y=100 are very similar line equations.
Finally, for each Line object you could get the size of the ArrayList keeping Points that fit on it, and throw away Lines that have less Points than what you want.
If you take a pair of points Pi and Pj, you can check in O(n) time which points lie on or near the line Pi Pj. There are O(n2) pairs, so you get an algorithm which is O(n3). Of course, if Pk is exactly on the line Pi Pj, you should no longer check lines Pi Pk and Pj Pk, because they will contain the same points as Pi Pj. However, this is not true if Pk is just close to Pi Pj.
I have made the algorithm displayed below. What it does is it calculates the formula of the line: y= kx+l; Then it makes two lines parallel to that one, one slightly raised and one slightly lowered->(y = kx+l-d and y=kx+l+d, d=tolerance). Then it goes through the rest of points and calculates the y for their x for the upper and lower parallel. If it's real value is between the calculated values it counts as beeing on the line.This is O(n^3).
Code:
public static void main(String[] args) {
Point[] points = generatePoints(5);
List<Set<Point>> lines = findLines(points,2,3);
lines.forEach((line)->{
System.out.println(Arrays.toString(line.toArray()));
});
}
private static List<Set<Point>> findLines(Point[] points,int tolerance,int minNumberOfPoints) {
List<Set<Point>> lines = new LinkedList<>();
for(int i=0;i<points.length;i++){
for(int j=i+1;j<points.length;j++){
//check if that line was all ready found
boolean hasBoth = false;
for(Set<Point> line:lines){
hasBoth =Boolean.logicalAnd(line.contains(points[i]),line.contains(points[j]));
if(hasBoth)
break;
}
if(hasBoth)
break;
int x1 = points[i].getX();
int y1 = points[i].getY();
int x2 = points[j].getX();
int y2 = points[j].getY();
double k = (double)(y1-y2)/(double)(x1-x2);
double l = y1-k*x1;
//y = kx + l -> line
//y1 = kx + l - tolerance -> lower parallel line
//y2 = kx + l + tolerance -> upper parallel line
//take a third point if for its x it gives a y3 where y1<=y3<=y2 then it should be part of the line
Set<Point> line = new HashSet<>();
line.add(points[i]);
line.add(points[j]);
for(int z=j+1;z<points.length;z++){
int x3 = points[z].getX();
int y3 = points[z].getY();
double y1Line = k*x3+l-tolerance;
double y2Line = k*x3+l+tolerance;
if(y1Line<=y3 && y3<=y2Line)
line.add(points[z]);
}
lines.add(line);
}
}
lines = lines.stream().filter((set)->{
return set.size()>=minNumberOfPoints;
}).collect(Collectors.toList());
return lines;
}
private static Point[] generatePoints(int number) {
Point[] points = new Point[number];
Random r = new Random();
for(int i=0;i<number;i++){
points[i] = new Point(r.nextInt(10), r.nextInt(10));
}
return points;
}
private static class Point{
private int x;
private int y;
public Point(int x,int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
#Override
public String toString() {
return "("+x+","+y+")";
}
}
You could use Hough transformation to detect lines. I experienced hough transformation while detecting features in images. It basically uses polar representation of lines to detect them. Although I think opencv is out of the context for what you want to do, I still want to share the hough line detection page with you which explains the algorithm pretty clearly.
http://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/hough_lines/hough_lines.html
There is also this source which I had found to be useful :
https://www.cs.sfu.ca/~hamarneh/ecopy/compvis1999_hough.pdf
I need to use information gathered from my main method in a different method within the same class. Is that possible? If so, how do I go about doing so? Basically I have to gather the info in main method and implement it in the other. Help!
If I gain information say:
import java.util.Scanner;
public class MyClass
{
public static double main (String[] args)
{
double x, y, z;
Scanner scan = new Scanner(System.in);
System.out.print ("Please enter x value: ");
x= scan.nextDouble();
System.out.print ("Please enter y value: ");
y= scan.nextDouble();
System.out.print ("Please enter z value: ");
z= scan.nextDouble();
}
public static void OtherMethod()
{
int a=0;
while(x<y)
{
a++;
double b=x* (z/100);
x+=b;
}
System.out.println("After " + a + " time at " + z+ "%, you will have " + "$" + x);
}
}
It sounds like you are asking how to pass arguments to a function.
Try writing:
public static void OtherMethod(double x, double y, double z)
Inside Main:
OtherMethod(x,y,z)
Yes. If you change the first line of OtherMethod to
public static void OtherMethod(double x, double y, double z)
then you can call it from main with
OtherMethod(x, y, z);
which makes the x, y, z defined in OtherMethod equal to the x, y, z defined in main, for the purposes of the one method call.
Gratuitous advice
For the record, there are a few bad programming practices in your code snippet. It's OK for now, since you're a beginner, but don't make a habit of any of them.
Single letter variable names. It's not obvious to someone working on this code that x is an amount of money, y is your savings target, z is the interest rate, and so on. You should use full words or even multiple words for your variables. Like savingsTarget and interestRate.
Inconsistent spacing and indentation make code hard to read.
Most people prefer not to put the { character on a line by itself. Put it at the end of the previous line instead.
You've used floating point types for money. Don't ever store an amount of money in a double or a float variable. These aren't designed for accurate mathematics with decimals. Learn to use the BigDecimal class instead.
Having static methods instead of creating objects is often indicative of poor design. It also makes big programs much more difficult to test, if there are many static methods.
Method names should begin with a lower case letter. It makes your code a little easier to follow.
Just a few things to think about for your future programming efforts.
declare double x, y, z; as class level static attibutes -
private static double x;
private static double y;
private static double z;
Inside your main method then you can call OtherMethod();