Generating several random double numbers in java - java

Every time when I try to generate random coordinates of city in this way,
public City () {
super();
this.x = Math.random()*200;
this.y = Math.random()*200;
}
I get the same values for the X and Y, which means that all cities are on same line on map. My question is how to avoid this? How to create different coordinates? Thanks.

I assumed a class like this:
class City {
private double x;
private double y;
public City() {
super();
this.x = Math.random() * 200;
this.y = Math.random() * 200;
}
#Override
public String toString() {
return "City [x=" + x + ", y=" + y + "]";
}
}
When I create new City objects I get (as it should be expected by the Math API) different values:
City [x=10.552289272723247, y=28.548756787475504]
City [x=58.96588997141927, y=146.87205149574288]
City [x=186.69728798772306, y=179.3787764147533]
Don't get me wrong - maybe at the point where you check the values you use by mistake twice the same?

To get different double values use java.util.Random class. Below, there's an example, it prints four different double values:
java.util.Random random = new java.util.Random();
System.out.println(random.nextDouble());
System.out.println(random.nextDouble());
System.out.println(random.nextDouble());
System.out.println(random.nextDouble());

Use java.util.Random.
Example:
Random random = new Random();
int x = random.nextInt(11); // from 0 to 10
double y = random.nextDouble(); // from 0 to 1

You must do wrong something else which is not in question.
public static void main(String[] args) {
double x = Math.random() * 200;
double y = Math.random() * 200;
System.out.println(x + ":"+y);
}
consider above code snap and you will get different x and y values..!
Please make sure that you are using new keyword every time while creating object of city.

Related

How to get the nearest Vector to a given target from a list

So imagine I've created a Vector class with two variables x and y in Java:
public class Vector {
private int x;
private int y;
public Vector(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY(){
return this.y;
}
}
Then I've craeted an ArrayList of vectors:
private List<Vector> vecs = new ArrayList<Vector>();
I've created in that list:
8,9
10,5
83473834,938849584985
etc ...
Now I want to get the closest vector to another vector.
Example:
private List<Vector> vecs = new ArrayList<Vector>();
private Vector vec = new Vector(1,1);
for(Vector vector:vecs) {
//What do i put here??
}
So what do i put in the for loop to make it select the nearest vector from the vector list?
I would start by adding a method to the Vector class, distanceTo, that calculates the distance from this vector to another one:
public double distanceTo(Vector vec) {
double dx = x - vec.x; //calculate the diffrence in x-coordinate
double dy = y - vec.y; //calculate the diffrence in y-coordinate
return Math.sqrt(dx*dx + dy*dy); //use the distance formula to find the difference
}
And then you can write the following method that returns the closest vector in a list to a given vector:
public static Vector closest(Vector target, List<Vector> list) {
Vector closest = list.get(0); //this variable will kep track of the closest vector we have found yet. We simply start with the first one
for(int i = 1; i < list.size(); i++) { //loop over the list, skipping the first entry
Vector curr = list.get(i); //get the current vector from the list
if (target.distanceTo(curr) < target.distanceTo(closest)) //if the current vector is closer to target than the closest one yet
closest = curr; //keep the current vector as the new closest one
}
return closest; //return the resulting vector
}
This method can then be used like this:
Vector target = new Vector(1, 2);
List<Vector> vecs = new ArrayList<Vector>();
vecs.add(new Vector(-2, 6));
vecs.add(new Vector(1, 3));
vecs.add(new Vector(4, 0));
vecs.add(new Vector(8, -1));
Vector closest = findClosest(target, vecs);
As you can see I tried to explain the code as best as I could, but feel free to ask any further questions!
EDIT another method is:
public double distanceTo(Vector vec1,Vector vec2) {
double dx = vec2.x - vec1.x; //calculate the diffrence in x-coordinate
double dy = vec.y - vec1.y; //calculate the diffrence in y-coordinate
return Math.sqrt(dx*dx + dy*dy); //use the distance formula to find the difference
}
This is if you can't put it into the vector class
This is a basic programming question. It is not related to OpenGL. A simple linear search could look as follows:
private List<Vector> vecs = new ArrayList<Vector>();
private Vector vec = new Vector(1,1);
Vector minDistanceVector = null;
int minDistanceSquared = Integer.MAX_VALUE;
for(Vector vector : vecs) {
//Calculate the distance
//This could be a member function of Vector
int dx = vector.getX() - vec.getX();
int dy = vector.getY() - vec.getY();
int squaredDistance = dx * dx + dy * dy;
if(squaredDistance < minDistanceSquared) {
minDistanceSquared = squaredDistance;
minDistanceVector = vector;
}
}
After that, you will have the closest vector in minDistanceVector. I chose Euclidean distance because this is probably what you want. But you could use any other distance, of course.
If you want something more efficient, you may want to build some acceleration data structure over the points and query that one (e.g. grid, kd-tree, quadtree...).

Comparing class attributes

I want to write a method that compares the attributes of two objects from the same class. Say I'v got point1 & point2 of the Point class, which have the attributes of:
public class Point{
private double x;
private double y;
private double z;
[...] */constructor and methods*/[...]
}
public static void main (String[] args){
Point point1 = new Point(5, 10, 20);
Point point2 = new Point(0, 5, 10);
}
I want to compare the x, y, and z values of point1 & point2 against each other but I have no idea how to do so. How would I differentiate between the different values in the code block of a method? This is the theoretical method I would write if I could:
public double comparePoints(Point a, Point b){
if (x1 < x2){
System.out.println("Point b has the bigger x-value");
return x2;
}
etc.
}
Any ideas how to do this?
You have already got good answers to your questions, i.e comparing using the comparator interface, using getter\setter to safely access the properties when they are declared private or access the property from each of the objects using obj1.x and obj2.x. It depends on the exact requirement what approach you want to take. The following piece of code that i have updated does a basic comparison of the attributes of two objects.
public class Point {
private double x;
private double y;
private double z;
//Constructor
Point(double l,double m,double n){
this.x = l;
this.y = m;
this.z = n;
}
//main method
public static void main (String[] args){
Point point1 = new Point(5, 10, 20);
Point point2 = new Point(0, 5, 10);
//Object that is created with the greater value
Point point3 = comparePoints(point1,point2);
System.out.println("-----The greater value of property, "
+ "between the two compared objects is as below----");
System.out.println("x ="+point3.x);
System.out.println("y ="+point3.y);
System.out.println("z ="+point3.z);
}
//Compare method declared static, for the satic main method to access
public static Point comparePoints(Point a, Point b){
System.out.println("Values in Object a = "+a.x+""+a.y+""+a.z);
System.out.println("Values in Object a = "+b.x+""+b.y+""+b.z);
System.out.println("Point a has the bigger x-value");
Point h = new Point(0,0,0);
if (a.x < b.x){
h.x = b.x;
}
else{
System.out.println("Point a has the bigger x-value");
h.x = a.x;
}
if (a.y < b.y){
System.out.println("Point b has the bigger y-value");
h.y = b.y;
}
else{
System.out.println("Point a has the bigger y-value");
h.y = a.y;
}
if (a.z < b.z){
System.out.println("Point b has the bigger z-value"+b.z);
h.z = b.z;
}
else{
System.out.println("Point a has the bigger z-value"+a.z);
h.z = a.z;
}
return h;
}
}
if you want to get one of the attributes of on object, you have two choices :
1/ using getter methods :
a.getAttributeX(Point) { ...}
2/ once creating an object Point you would be able to use this:
if(a.x < b.x) then....
PS: It's always safe to use getter methods !

Iteratation through variables of an objects (java)

I have a class Room with the following constructor:
public Room (int x, int y, int z, int Stockwerk) {
this.x = x;
this.y = y;
this.z = z;
this.Stockwerk = Stockwerk;
}
In another class I want to calculate the similarity of two rooms by using the Euclidean distance. Therefore I want to iterate trough the object room to compare the first value(x) of room1 with the first value(x) of room2, the second(y) with the second(y) and so on. (The code below describes how I tried to get a result). Is there any option to iterate through the object room?
Iterator itrRoom1 = room1.iterator();
Iterator itrRoom2 = room2.iterator();
while (itrRoom1.hasNext()) {
while (itrRoom2.hasNext()) {
int value1 = itrRoom1.next();
int value2 = itrRoom2.next();
}
//this is the function how I get the similarity of two rooms (euclidean distance)
squareSubtraction = squareSubtraction + Math.pow(Math.abs(value1 - value2)), 2);
}
distance = Math.sqrt(squareSubtraction);
You do it with a very complicated way and Iterator is not needed.
If you want to get the euclidean distance, you only have to parse these two instances of Room to be compared. I assume your Room class has the getters.
You can use the following method with the arbitrary number of arguments based on looping through of all instances of Room given.
public static void main(String[] args) {
Room room1 = new Room(10,12,2,0);
Room room2 = new Room(4,8,2,0);
Room room3 = new Room(7,5,2,0);
Room room4 = new Room(10,2,2,0);
double result = similarity(room1, room2, room3, room4);
}
public static double similarity(Room ... r) {
double sum = 0;
for (int i=0; i<r.length-1; i++) {
double a = Math.pow(r[i].getX() - r[i+1].getX(), 2);
double b = Math.pow(r[i].getY() - r[i+1].getY(), 2);
sum += a + b;
}
return Math.sqrt(sum);
}
This is giving you the result:
9.38083151964686
You can't iterate fields like that. You could iterate fields using reflection, but don't.
You only have 3 values. Just use them.
long dx = room1.getX() - room2.getX();
long dy = room1.getY() - room2.getY();
long dz = room1.getZ() - room2.getZ();
double distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
Note that dx and the others are declared long, so dx * dx won't overflow, and dx * dx is much faster than Math.pow(dx, 2).
It's actually even less code than what you were trying to do.

Java - how to get maximum result of a calculation

We are working on creating object and driver classes. I have an object class that does various things to a moving exploratory robot.
What I need to do now is create a method that returns the largest distance that the robot moved in one single move command. I also need to return the time that it took to move that distance.
Here's the relevant code for that so far:
{
private int xcoord, ycoord; //Cartesian coordinates of the robot
private int identification; //Identification number of the robot
private double rate; //Rate at which the robot explores
private double traveled; //Distance the robot has travelled
private double timeSpent; //Time spent travelling
private double longestLeg; //Longest leg of the journey
private double longestLegTime; //Time on the longest leg
//Sets up a robot with the given ID number and beginning x and y coordinates
public Robot (int id, int x, int y)
{
identification = id;
xcoord = x;
ycoord = y;
traveled = 0;
rate = 5.0;
}
//Has the robot travel to the set coordinates
public double setDestination (int x, int y)
{
double distance = Math.pow(x - xcoord, 2) + Math.pow(y - ycoord, 2);
traveled += Math.sqrt(distance);
xcoord = x;
ycoord = y;
timeSpent += Math.sqrt(distance)/rate;
return traveled;
}
//Gets the time spent travelling
public double getTimeSpent()
{
return timeSpent;
}
//Sets the rate at which the robot travels
public void setRate(double setrate)
{
rate = setrate;
}
//Returns longest leg of the robot's travels
public int getLongestLeg()
{
return longestLeg;
}
//Returns time of longest leg
public double getLongestLegTime()
{
return longestLegTime;
}
I'm not allowed to use if statements or loops yet, so it will have to be using Math.max I'm guessing. I tried using it, but it gave me an error saying that it required an int but I supplied a double.
Any suggestions would be awesome. Thanks!
If you are able, I have one final problem with the code as well. I need to create a method that would get the distance between two Robot objects. I'm not even sure how to start this one since we haven't really worked with it yet. A suggestion on how to even start this would be great. Thanks again.
To avoid casting, this should work:
longestLeg = Math.max(distance, longestLeg);
If you are getting an error about requiring an int, it probably means one of your parameters was an int when it shouldn't be. Can't be sure without seeing exactly how you were calling it, but I suspect it may have been to do with the fact getLongestLeg() is returning longestLeg as an int when it's actually a double. I would suggest changing that method to:
//Returns longest leg of the robot's travels
public double getLongestLeg()
{
return longestLeg;
}
In terms of your second question, to calculate the distance between another robot, the calcDist() method should probably look something like this:
public double calcDist(Robot other)
{
return Math.sqrt(Math.pow(this.getX() - other.getX(), 2) + Math.pow(this.getY() - other.getY(), 2));
}
If i got your question right you just wanted to use the Math.max() with Integers.
Try
(int) Math.max()

How can I move a point and print the new position?

I'm new to Java and I received an assignment that asks me to write a class called PointerTester that has two Points as instance variables. I need to initialize one of these at coordinate (0.0,0.0) and one at (10.0,12.0). Then I need to move each point by +2.0 in x and -3.0 in Y, query the coordinates of the points, and print out the values.
So far I have this:
public class PointerTester{
/*instance variables*/
private double pointOneX;
private double pointOneY;
private double pointTwoX;
private double pointTwoY;
private double deltaX;
private double deltaY;
/*constructor to initialize*/
public PointerTester (){
pointOneX = 0.0;
pointOneY = 0.0;
pointTwoX = 10.0;
pointTwoY = 12.0;
deltaX = 2.0;
deltaY = -3.0;
}
/*constructor to initialize to specific value*/
PointerTester(double pointOneX, double pointOneY, double pointTwoX, double pointTwoY){
this.pointOneX = pointOneX;
this.pointOneY = pointOneY;
this.pointTwoX = pointTwoX;
this.pointTwoY = pointTwoY;
}
/*command to change value*/
public void moveBy(double deltaX, double deltaY){
this.pointOneX = this.pointOneX + deltaX;
this.pointOneY = this.pointOneY + deltaY;
this.pointTwoX = this.pointTwoX + deltaX;
this.pointTwoY = this.pointTwoY + deltaY;
}
/*Queries*/
public double getOneX(){
return pointOneX;
}
public double getOneY(){
return pointOneY;
}
public double getTwoX(){
return pointTwoX;
}
public double getTwoY(){
return pointTwoY;
}
/*print values*/
public static void main(String[] args){
PointerTester pointOne = new PointerTester();
PointerTester pointTwo = new PointerTester();
System.out.println("Point One after move (" + pointOne + ")");
System.out.println("Point Two after move (" + pointTwo + ")");
}
}
I cannot figure out how to correctly output the values or if I am completely wrong in working on this problem.
Edit It seems I needed to use this code that I at first thought was supposed to be separate
public class Point{
public double x;
public double y;
public Point(double x, double y){
this.x = x;
this.y = y;
}
public void setX(double x){
this.x = x;
}
public void setY(double y){
this.y = y;
}
public double getX(){
return x;
}
public double getY(){
return y;
}
}
How do I incorporate this into my code?
I think to get started you should have a separate class called "Point" that encapsulates an X and Y value, and includes a "moveBy" method. It could also implement "toString()" such that "System.out.println" will print something nice for it. [Edit: Or just use java.awt.Point.]
Beyond that, I'll leave that for you to do as your homework.
You might want to use some Point objects.
Point p1 = new Point();
Point p2 = new Point(10,12);
you can then use the setLocation or translate methods found in the point class. Maybe the whole thing would look something like this? Hope this helps.
main(){
//make some points
Point p1 = new Point();
Point p2 = new Point(10,12);
//move our points
p1.translate(2,-3);
p2.translate(2,-3);
//print our points
System.out.println(p1);
System.out.println(p2);
}
You can implement the toString method. There are examples here:
http://www.javapractices.com/topic/TopicAction.do?Id=55
You're trying to print the PointerTester object instead of the values contained within. System.out.println(pointOne.getOneX()) should at least stop throwing exceptions and allow you to print correctly.

Categories