Is it possible to check all coordinates in Point2D.Double array? - java

I have x,y coordinates stored in a Point2D.Double type.
Code:
private Point2D[] block1 = new Point2D[99]
block1[0] = new Point2D.Double(12,14);
block1[1] = new Point2D.Double(15,16);
block1[2] = new Point2D.Double(20,20)
//etc all to 99.
//this can run about 10 times creating 10 different sets of x,y coordinates.
Want to iterate through all the arrays see if a specific coordinate is already there. If it is return true. Not sure on the best way to do it.
So I know that I will need a for/if loop.
Example: I want to check to see if (15,16) is there:
for(Point2D block[] : block1){
if(block.getX() == 15 && block.getY() == 16){
System.out.println("This is true");
}
}
So I want it to search through all the arrays to see if there is a (15,16). I can image this syntax is along the right lines but it is not right.

This approach will gets as close as possible to your desired syntax:
Point2D target = new Point2D.Double(15, 16);
for(Point2D block : block1){
if(target.equals(block)){
System.out.println("This is true");
}
}
By the way, you mentioned you want 10 times 10 different sets of coordinates, so you need to change the 99 to 100, otherwise you will crash the array:
Point2D[] block1 = new Point2D[100];

There's an error in this line:
for(Point2D block[] : block1){
if 'block1' is an array, while iterating 'block's type should be of the array's type. Namely, just Point2D - rather than Point2D[].
As a first step, try this snippet out:
for (Point2D block : block1) {
if (block.getX() == 15 && block.getY() == 16) {
System.out.println("Found it");
}
}

Almost there, now just extract that to a method:
public boolean containsPoint(Point2D[] points, int x, int y) {
for(Point2D block : points){
if(block.getX() == x && block.getY() == y){
return true;
}
}
return false;
}
...
/* calling the method */
if(containsPoint(points, 10, 10)) { // do stuff }

Related

How to get and compare integer array from a list in a list? [duplicate]

This question already has answers here:
Comparing two integer arrays in Java
(10 answers)
Closed 1 year ago.
I have a program that uses a java.awt robot to get a picture of the screen and then cycle through the pixels and categorize certain colors in blocks in a list of lists of integer arrays. I have a List<List<int[]>> blocks. The first List is a list of all the blocks, the second list is a list of all the pixels in the blocks, and the integer array is 2 value that are the x and y of the pixel. I first tried to use a for loop through all the blocks with list.contain's to find the array, but that always returned false. I am trying now to use a loop like this to find them.
boolean continuer = false;
boolean found = false;
for (List<int[]> thisBlock : blocks) {
int[] newInt = new int[2];
newInt[0] = i;
newInt[1] = j;
for (int[] thisInt : thisBlock) {
if (thisInt == newInt) {
continuer = false;
found = true;
System.out.println("Found pixel in block");
break;
}
if (found) {
break;
}
}
if (found) {
break;
}
}
if (!found) {
continuer = true;
}
This also returned false always. Any help would be greatly appreciated.
Arrays cannot be compared with == operator. There are methods that Arrays Class provides to perform operations on Arrays. Use Arrays.equals(thisInt,newInt) instead of thisInt == newInt

Finding the next location in a grid

I am creating a method to help me find the next position in a grid of islands/objects in a 3d world(but ignoreing the Y coordinate for now), they have a distance of 200 for each island(islandDistance).
What I currently have is this:
public static Location findLocation(String latest,String server) {
if (latest == null) {
latest = sql.findLatestIslandEntry(server);
if (latest != null && latest.isEmpty()) // first creation
latest = "0,4,0";
else if (latest == null)
return null;
}
String split[] = latest.split(",");
List<String> locationString = Arrays.asList(split);
List<Double> locations = new ArrayList<>();
for (String xyz : locationString) {
locations.add(Double.valueOf(xyz));
}
String world = CC.getSTDConfig().getString("worldname");
Location l = new Location(Bukkit.getWorld(world),0,4,0);
if (locations.get(0) <= 0) {
l.setX(Math.abs(locations.get(0)) + islandDistance);
} else {
l.setX(0 - locations.get(0));
}
if (locations.get(2) <= 0) {
l.setZ(Math.abs(locations.get(2)) + islandDistance);
} else {
l.setZ(0 - locations.get(2));
}
return l;
}
Even before testing I could see that this wouldn't work. I would end always adding to both x and z when thats not always what I want. I made an example of the dataset I want as output here:
Basicly what I want to is to get the next position depending on how many I have already inserted and maybe the last one inserted ? thats the info I use in my code currently atleast. Say I just inserted island number 25 and now want island 26 I should get the result 0,600(the order can be different I just want to fill the grid out)
You want to generate integer coordinates ordered by Euclidean distance. To diminish calculation, it is enough to generate coordinates in the first octant (for 2d case), so X and Y are non-negative and Y<=X. For every calculated (X,Y)pair just generate also (X,-Y), (-X,Y), (-X,-Y),(Y,X),(Y,-X), (-Y,X), (-Y,-X) (except for zero components).
Create priority queue where comparison key is sum of squares (squared distance X*X+Y*Y). Push (0,0) item. At every step extract minimum item (MX, MY) and push next points
Output MX, MY and all permutations
if (MY = 0) and (MX < SomeBorderValue)
push (MX+1, 0)
if MY < MX
push (MX, MY+1)

Odd returning of ArrayList#size()

I am trying to get a random ArrayList in a HashMap, and when I look at all the ArrayLists in the HashMap the size of everything is 2 as it should.
The problem occurs when I try to add an ArrayList from the Hashmap into another. It then returns the size as 0 even though the size of all lists in the HashMap are 2. Does anyone see why?
for(Point p : defensePossibilities.keySet())
System.out.println(defensePossibilities.get(p).size());
ArrayList<Point> points = new ArrayList<>();
while(points == null) {
try {
int random = rnd.nextInt(defensePossibilities.size());
points.addAll(
defensePossibilities.get(random));
} catch(Exception e) {}
}
System.out.println("PointsSize: " + points.size());
int piece2 = rnd.nextInt(points.size());
This is what it returns in the stacktrace
2
2
2
2
2
2
2
2
PointsSize: 0
Exception in thread "Thread-0" java.lang.IllegalArgumentException: bound must be positive
at java.util.Random.nextInt(Unknown Source)
at me.xthegamerplayz.FirstGame.board.White_AI.move(White_AI.java:95)
at me.xthegamerplayz.FirstGame.board.ChessBoard.tick(ChessBoard.java:29)
at me.xthegamerplayz.FirstGame.board.ChessBoard.<init>(ChessBoard.java:21)
at me.xthegamerplayz.FirstGame.Game.render(Game.java:124)
at me.xthegamerplayz.FirstGame.Game.run(Game.java:70)
at java.lang.Thread.run(Unknown Source)
Line 95 is
int piece2 = rnd.nextInt(
Why is the size of points 0 if all the ArrayLists in the HashMap are at the size of 2?
replace points == null with points.isEmpty()
points variable is not null because you assign points variable an arraylist before the while loop. I assume what you want to do is to check while the poinst list is empty. So making the suggested change will solve your problem.
for(Point p : defensePossibilities.keySet())
System.out.println(defensePossibilities.get(p).size());
ArrayList<Point> points = new ArrayList<>();
while(points == null) { // points is not null, it is just empty
// replace points == null with points.isEmpty()
try {
int random = rnd.nextInt(defensePossibilities.size());
points.addAll(
defensePossibilities.get(random));
} catch(Exception e) {}
}
System.out.println("PointsSize: " + points.size());
int piece2 = rnd.nextInt(points.size());
points not is null because you have instantiated it.
ArrayList<Point> points; this is null
So replace your code
for(Point p : defensePossibilities.keySet())
System.out.println(defensePossibilities.get(p).size());
ArrayList<Point> points = new ArrayList<>();
while(points.isEmpty()) {
try {
int random = rnd.nextInt(defensePossibilities.size());
points.addAll(
defensePossibilities.get(random));
} catch(Exception e) {}
}
System.out.println("PointsSize: " + points.size());
int piece2 = rnd.nextInt(points.size());
UPDATE
change
points.addAll(defensePossibilities.keySet());
2 UPDATE
public V get(Object key) Returns the value to which the specified key
is mapped, or null if this map contains no mapping for the key.
So
ArrayList<Point> a = new ArrayList<>();
a.addAll(defensePossibilities.keySet());
int random = rnd.nextInt(defensePossibilities.size());
points.add(a.get(random))
Your actual problem, after using isEmpty() instead of == null, is an ArrayIndexOutOfBoundsException.
In your code the value of random can be as large as the size of your List. Let's say you have 10 Objects inside and random is 10:
defensePossibilities.get(random); // 10 object = indexes 0 to 9, but not 10!
Remember that Lists, as Arrays do, start indexing by 0.
} catch(Exception e) {
System.out.println(e.toString());
}
And you'll se what i mean. ;o)

Java tron Collision,Combobox

I'm trying to do my school project "Tron". I'm newbie when it comes to programming... I did some collisions with arraylist and they are working fine.But I can't do collision snake with other object ... I'm using this:
snake1x and snake1y are coordinates of first snake and obstacleX is arraylist that contains coordinates of other object.
for(int l=0;l<obstacleX.size();l++) {
if((snake1x == obstacleX.get(l)) && (snake1y == obstacleY.get(l))) {
running = false;
}
}
I have the object already drawn in my game but snake will just pass throught it ... :(
the weird thing is that I did this with similiar method on collision between snakes and it works fine :)
My second problem is with combobox and choosing a color for snake..
if (snake1 = true) {
for (int p = 0; p < pathx1.size(); p++) {
g.setColor(Color.white);
g.fillRect(pathx1.get(p), pathy1.get(p), width, height);
I could simply give it colour like this but I need to choose it from the combobox
and that where I am lost :)
I will appreciate any help or anything that could improve my work like adding other things and something like that thanks~~ :-)
import java.util.*;
public class AutoBoxingTest
{
public static void main(String[] args) {
int i = 1;
Integer intObj = 1;
ArrayList<Integer> intArray = new ArrayList<>();
intArray.add(new Integer(1)); // Forcefully create a new Integer object
intArray.add(1);
if(i==intArray.get(0))
System.out.println("Equals");
else
System.out.println("Not Equals");
if(intObj==intArray.get(0))
System.out.println("Equals");
else
System.out.println("Not Equals");
if(intObj==intArray.get(1))
System.out.println("Equals");
else
System.out.println("Not Equals");
}
}
When you run this program, you get the result
Equals
Not Equals
Equals
Notice the difference between intArray.get(0) and intArray.get(1). Even though both are 1, they are different objects.

pathfinding search crash if distance is longer than 2

The assignment is to create a game of reversi. I have it working except for moves that involve changing more than one chip
x o
o o
o o o
# <-- the # is x's move that crashes the game.
, in which case the program crashes. The crash takes place somewhere in isPlayable().
Where am I going wrong?
//there are 7 more such methods for different directions
// (down, left, right, diagonals).
public void searchN(int x, int y, int increment){
if(x-increment>=0){
if(this.isPlayed(x-increment,y)){
if(increment>1 && chips[x-increment][y]==turnColor){
//turnColor is an int value 1 or 2
// (0 represents unplayed space in chips[][])
// 1 corresponding to white, 2 corresponding to black.
playable[0] = true;
leads[0] = false;
} else {
if(chips[x-increment][y]!=turnColor){
leads[0]=true;
}
}
}else
leads[0]=false;
}else
leads[0]=false;
}
public boolean isPlayable(int x, int y){
this.searchN(x,y,1); //7 other directions are searched
while(leads[0]||leads[1]||leads[2]||leads[3]||leads[4]
||leads[5]||leads[6]||leads[7]){
int i = 2;
if(leads[0]) // 7 other directions are searched given that their marker is true.
this.searchN(x,y,i);
}
if(playable[0]||playable[1]||playable[2]||playable[3]||playable[4]
||playable[5]||playable[6]||playable[7])
return true;
else
return false;
}
Per your comment, it sounds like you're experiencing a hang, not a crash. When a program hangs, you should look for places where the program can get indefinitely "stuck". The prime suspect in isPlayable is your while loop. As long as any of the eight booleans are true it will never complete.
I would add some logging so you can see what's happening:
while(leads[0]||leads[1]||leads[2]||leads[3]||leads[4]
||leads[5]||leads[6]||leads[7]){
System.out.println("leads[0]: " + leads[0]);
System.out.println("leads[1]: " + leads[1]);
// etc.
int i = 2;
if(leads[0]) // 7 other directions are searched given that their marker is true.
this.searchN(x,y,i);
}
Once you've verified that this is the problem, start looking into your search methods to figure out why its happening.

Categories