Is there a way to have a static method such that it returns a Vector object (with a simple integer x and y value as fields) which is a Vector multiplied by an int value argument. However, there are no new objects made, i.e, the object assigned to the return value is changed instead of there being a new Vector created?
The following code does not achieve this:
public class Vector{
public int x,y;
public Vector(int x,int y){
this.x = x;
this.y = y;
}
//Important code starts
public static Vector mult(Vector v,int a){
return new Vector(v.x*a,v.y*a);
}
//Important code stops
}
This code is what I'm after but it's too messy:
public static Vector mult(Vector v1,Vector v2,int a){
v1.x = v2.x*a;
v1.y = v2.y*a;
}
Is there an alternative?
Why not add:
public void multiply(Vector otherVector, int a){
x = otherVector.x * a;
y = otherVector.y * a;
}
to your Vector class.
Do you mean?
public void mult(double a) {
x *= a;
y *= a;
}
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());
}
}
}
Im trying to add my anonymous objects from a class to a Hashtable. I created my Hashtable as my teacher wants but there is one problem. I have to get x and y values one of my Objects. But System cannot find x anyway.
public class HashDatastructure{
public static void main(String[] args){
java.util.Hashtable kreise = new java.util.Hashtable();
for(int i = 0; i < 6; i++){
kreise.put(new Integer(i), new Kreis(120, 120, 60));
}
System.out.println(kreise.get(3).toString() + " is 4. Object
and this Object's X Value: "
+ kreise.get(3).x + " || Y Value: ");
}
}
And here it is my Kreis Class:
public class Kreis extends Object{
public int x; //Mittelpunkt-x
public int y; // Mittelpunkt-y
public int radius;
public final double PI = 3.14159; //Constant Variable for pi
public static int kreisCounter = kreisZaehler();
public static int counter = 0;
public Kreis(int x, int y, int radius){
this.x = x;
this.y = y;
this.radius = radius;
kreisCounter();
}
private static int kreisZaehler(){
counter++;
return counter;
}
public void setRadius(int wert){
radius = wert;
}
public double getFlaeche(){
return radius * radius * PI;
}
public double getUmfang(){
return 2 * radius * PI;
}
}
I don't know what you mean by "anonymous objects," but you're using raw types, which is generally not a good idea. Instead, tell the compiler what kind of object kreis contains:
java.util.Hashtable<Kreise> kreise = new java.util.Hashtable<>();
// ----------------^^^^^^^^---------------------------------^^
Then, the compiler will know that get returns a Kreis object, which has x and such. (Side note: Probably better to make x private and provide an accessor like getX for it.)
More to explore in the Generics Java Tutorial.
If for some reason you have to use raw types, you can cast to Kreis on retrieval:
// NOT recommended
System.out.println(kreise.get(3).toString() + " is 4. Object and this Object's X Value: "
+ (((Kreise)kreise.get(3)).getX() + " || Y Value: ");
// -----------------^^^^^^^^^-------------^-^^^^^^
(Note I'm assuming you make x private and provide an accessor for it.)
public class InitializationTest {
private int x;
private int y;
private int sumOFXandY = x + y;
public InitializationTest(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getSumOFXandY() {
return sumOFXandY;
}
}
class Tester {
public static void main(String[] args) {
InitializationTest initializationTest = new InitializationTest(5, 6);
System.out.println(initializationTest.getX());
System.out.println(initializationTest.getY());
System.out.println(initializationTest.getSumOFXandY());
System.out.println(initializationTest.getX() + initializationTest.getY());
}
}
Output:
5
6
0 //Why not 11?
11
In the example above my brain cannot understand such simple thing - a revelation.
When the class is created, its fields are initialized with default values. In this case those are 0.
Upon calling the constructor x is initialized with 5 and y is initialized with 6. Why then sumOFXandY is somewhere aside and still is initialized with 0 even after calling the constructor. Why is not it initialized with 5 + 6 = 11 ?
Because it(sumOFXandY) cannot be re-initialized after the constructor gets executed. When you create an object, it initializes the instance variables that are initialized inline (here it is sumOFXandY = x + y). Then the constructor block gets executed.
To solve this, move sumOFXandY = x + y inside the constructor.
I'm stuck on this question for a couple of days now and would really like to get some help.
I am given a 2 dimensional point in the range of (0-1 not including 1), such as (0.5,0.2), and N other points (also in the range of 0-1).
The first part of the question is to implement the "dumb" algorithm, which when given a certain point will find the point with the shortest distance from it, which has a complexity of O(N).
The part I'm stuck at, requires to build a Matrix K on K, where each "cell" will contain the points that belong to that cell. Once done, when given the original point I will need to search for the point with the shortest distance to it only in some of the cells and not the entire Matrix, which should result better complexity.
My original thought is to devide the points so that each block will have an arraylist of points that belong to him, and then to somehow go through the main block(the one that the original point belongs to) and continue by going through it's neighbors, however implementing it hasn't been very successful.
I would highly appreciate any help/ advice.
Below is what I currently have:
public class Point {
private double x;
private double y;
private Block b;
public Point(double x, double y)
{
this.x=x;
this.y=y;
}
public Point(double x, double y, Block b) //consrtuctor for complex case
{
this.x=x;
this.y=y;
b.points.add(this);
}
public double getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public double distance(Point p)
{
double res=0;
res = Math.sqrt(Math.pow(this.x-p.getX(),2)+Math.pow(this.y-p.getY(),2));
return res;
}
}
import java.util.ArrayList;
public class Block {
private int x;
private int y;
public ArrayList<Point> points;
public Block(int x, int y) {
points = new ArrayList<Point>();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
import java.util.Random;
public class ComplexCase {
private Block[][] blockMat;
public ComplexCase(int k, int n)
{
Random generator = new Random();
Point p1;
Block b1;
double x,y;
int bx1,by1;
int t;
t = 1/k;
blockMat = new Block[k][k];
for (int i =0;i<n;i++)
{
x = generator.nextDouble();
y = generator.nextDouble();
bx1 = (int) (x/t);
by1 = (int) (y/t);
b1 = new Block(bx1,by1);
p1 = new Point(x,y,b1);
}
}
public Block[][] getBlockMat() {
return blockMat;
}
public void setBlockMat(Block[][] blockMat) {
this.blockMat = blockMat;
}
}
package point;
//an array arr is populated with random x,y points using MyPoint then
public static void main(String[] args) throws IOException {
HashMap<MyPoint,Integer> map = new HashMap<MyPoint,Integer>();
Integer val =0;
for(int i = 0; i < arr.length ; i++)
{
map.put(arr[i],val);
}
}
//second file.
package point;
public class MyPoint implements Comparable<MyPoint>{
private int x;
private int y;
public MyPoint(int x1, int y1) {
x = x1;
y = y1;
}
public boolean equals(Object p) {
MyPoint p1;
try {p1 = (MyPoint) p;}
catch (ClassCastException ex) {return false;}
return (x == p1.x) && (y == p1.y);
}
public int hashCode() {
return ((y * 31) ^ x);
}
Here is my code MyPoint stores x y points. I'm using this code to get unique sets of x,y points with no duplicates.
My Question is how do I retrieve the x y values in MyPoint ? Is this an efficient way to use a HashMap to filter unique X,Y points. Also here is the HashCode I made.
Is there a better HashCode I could use?
An easy way would be to make getter methods for x and y:
public int getX(){
return x;
}
public int getY(){
return y;
}
As for a HashMap, you could have it map from X coordinates to a list of MyPoints with that X coordinate and unique Y coordinates (HashMap). However, if all you're looking for is uniqueness, you could just store every MyPoint in a set/ArrayList and see if a similar point already exists, using your .equals() method. Hope that helps!