public void fillWith(TileEntity tile){
for(int i = 0; i < this.height; i++){//for every x and y value
for(int j = 0; j < this.width; j++){
tile.x = j;
tile.y = i;
this.tiles.add(tile);
}
}
}
Okay so the above code is supposed to fill the level with a TileEntity tile. When I print out the x and y coords before the line "this.tiles.add(tile)", each tile has different coords. But when I print out the x and y coords of all of the tiles in the ArrayList "tiles", every single one is (9,9). They are all identical to the very last tile added to the arraylist. Thanks!
You keep adding the same object in your for-loop.
If you want to add different objects, you will need to create new instances using for example new TileEntity().
public void fillWith(){
TileEntity tile;
for(int i = 0; i < this.height; i++){//for every x and y value
for(int j = 0; j < this.width; j++){
tile = new TileEntity();
tile.x = j;
tile.y = i;
this.tiles.add(tile);
}
}
}
You are right that, in your code example, the values change every time you are in the loop, but because tile points to the same object every iteration, you will only change the x and y values within that object. (Java will not create a new object for you when you change x and/or y). When you add tile to the array this.tiles, it will reference the object you add - it will not make a copy of it.
All in all, tile and every object in your array will point to the same single instance of TileEntity.
You've succeeded in adding the same tile to the ArrayList 100 times. There's still only one object here, so the last update "wins": x = 9 and y = 9.
If you want different values, then you must add 100 different tile objects, each with their own distinct values.
You need to create new tile object each time in the loop,otherwise each time the existed tile pbject changes and remains with the last inserted values.
for(int j = 0; j < this.width; j++){
tile= new TileEntity();
tile.x = j;
tile.y = i;
this.tiles.add(tile);
}
Related
I am trying to make a game where the player can only see in a small radius around them. i'm attempting to do this by covering a 500X500 display with 1X1 black pixels that i can set active or inactive. The problem is that using a standered for loop to add them takes a large amount of time when the program launches and it slows the entire thing down. Any Solutions?
the pix object takes two paramaters(int x, int y)
code
public ArrayList<Pix> pixs= new ArrayList<>();
for(int i = 0; i<=500; i++)
{
for(int ii = 0; ii<=500; ii++)
{
pixs.add(new Pix(ii,i));
}
}
You are constructing 250000 instances of your Pix class. That will take some time.
Consider having a 2 dimensional array of booleans instead. Where false means the pixel is black.
You don't need to initialize the values yourself as they will default to false.
boolean[][] pixs = new boolean[500][500];
You can iterate over the structure with this:
for (int x = 0; x < 500; x++) {
for (int y = 0; y < 500; y++) {
System.out.println(pixs[x][y]);
}
}
And you can set a particular pix with
int x = 232;
int y = 455;
pixs[x][y] = true;
So, I am building a method to check a 2d array for a target value and replace each adjacent element with that target value. I have literally tried to brainstorm the solution to this for about an hour and I just want to know if anyone can help me with this, this is the code I have so far
public int[][] replaceValue(int n, int[][]y){
int [][]temp0 = new int[y.length][y[0].length];
int[]top, down ,left, right = new int[y[0].length];
for(int row = 0; row < y.length; row++){
for(int col = 0; col < y[row].length; col++){
temp0[row][col] = y[row][col];// new array so I wouldn't mess with the array passed in
}
}
for(int row = 0; row < temp0.length; row++){
for(int col = 0; col < temp0[row].length; col++){
top[row] = temp0[row-1][col];
down[row] = temp0[row+1][col];
right[row] = temp0[row][col+1];
left[row] = temp0[row] [col-1];
}
}
I got error messages such as I didn't initialize my top and left and right and down variables but I simply don't understand how the logic works for checking the adjacent elements and making sure the whole array is not replaced with the target value. Thanks
The question is a little confusing so I will try to interpret it.
What you are given is a 2-dimensional array with some integer values. Your function should scan the 2-d array, and if you find some target value,
return a 2-d array with the adjacent indices as the target value as well.
For example, if we have a 3x3 array and the target is 2...
1 1 1 1 2 1
1 2 1 ====> 2 2 2
1 1 1 1 2 1
Your problem is that you can't think of a way to change the value without changing the entire array to 2.
Solution One: You scan for the target value in the given array, but you update the values in the temporary array.
Solution Two: You scan the temporary array, and store whether or not it should be changed using a 2-d boolean array.
Solution One is much better in terms of efficiency (both memory and time), so I'll just give you my solution #2, and leave you to do Solution One on your own.
Also, please use more descriptive variable names when it matters :P (why is the input called temp??)
public static int[][] replaceValue(int target, int[][] currArray){
int[][] temp = new int[currArray.length][];
//get a boolean array of same size
//NOTE: it is initialized as false
boolean[][] needsChange = new boolean[currArray.length][currArray[0].length];
//copy the current array into temp
for(int i = 0; i < currArray.length; i++){
temp[i] = currArray[i].clone();
}
//Go through each value in the 2d array
for(int i = 0; i < temp.length; i++){
for(int j = 0; j < temp[0].length; j++){
//if it is the target value, mark it to be changed
if(temp[i][j] == target){
needsChange[i][j] = true;
}
}
}
//Go through each value in the 2d array
for(int i = 0; i < temp.length; i++){
for(int j = 0; j < temp[0].length; j++){
if(needsChange[i][j]){ //NOTE: same as "needsChange[i][j] = true;"
//Now, we will check to make sure we don't go out of bounds
//Top
if(i > 0){
temp[i-1][j] = target;
}
//Bottom
if(i + 1 < temp.length){
temp[i+1][j] = target;
}
//Left
if(j > 0){
temp[i][j-1] = target;
}
//Right
if(j + 1 < temp[0].length){
temp[i][j+1] = target;
}
}
}
}
//return the new array we made
return temp;
}
You have not initialized your local variables before first use. So you need to change your 3rd line to some thing like the below code:
int[] top = new int[temp[0].length], down = new int[temp[0].length],
left = new int[temp[0].length], right = new int[temp[0].length];
After that your code is compiled and you can check your logic.
I would like to take sets of every 3 elements from table, and then use them for some calculations. Let's say that my table is really big, e.g. 1000+ elements.
Tab elements are like like {x1,y1,z1,x2,y2,z2,...}.
I want to take the first three elements, do some calculations with them, take the next three elements, etc.
Here is my code so far:
double x=0;
double y=0;
double z=0;
for (int i =0; i<tab.length; i++)
x= (double)tab[i];
for (int j =0; j<tab.length; j+=2)
y= (double)tab[j];
for (int k =0; k<tab.length; k+=3)
z= (double)tab[k];
deathstar(x, y, z);
This is using only last 3 elements from tab and deathstar is printing calculation made only on last 3 elements. I was playing around with {}, but it didn't give me results that i wanted. Anyone have any solid idea how to take out every 3 elements from my table ? tab is defined outside of this code and is of type int[].
Thank You in advance for any thoughts about given issue.
Lose the increment part of the loop and increment after each element is gotten.
for (int i =0; i<tab.length;) {
X=(double)tab[i++];
Y=(double)tab[i++];
Z=(double)tab[i++];
//do something
}
This will grab three consecutive elements at a time and then do the calculation. Also checkS to make sure it won't go out of bounds.
double x=0;
double y=0;
double z=0;
int j = 1;
int k = 2;
for (int i =0; i<tab.length; i++)
{
if(i + j < tab.length && i + k < tab.length){
x= (double)tab[i];
y= (double)tab[i + j];
z= (double)tab[i + k];
deathstar(x, y, z);
}
}
You're missing a { after the last for, and so deathstar is only called after all loops finished. Better use { for every for-loop. You could find this easily using a Debugger.
Next, you will ask what's wrong with the logic and why yoou don't get the expected result, because now you would get deathstar(x1,y1,z1), deathstar(x1,y1,z2),.... Try the following (note: I'm assuming the length of tab is indeed a multiple of 3):
for(int i = 0; i < tab.length; i += 3) {
x = tab[i];
y = tab[i+1];
z = tab[i+2];
deathstar(x, y, z);
}
This way your code looks much cleaner.
for (int i =3; i<tab.length; i+=3){
tab[i-1]
tab[i-2]
tab[i-3]
}
maybe this approach will help you
Here I have a loop in a loop to fill level but when it runs through it fills each ArrayList(Integer) the same way, so in the end every row is the exact same. I just can't figure out how this is even possible, when I am filling in every single field one by one.
//... level = new ArrayList<ArrayList<Integer>>();
for(int x = 0; x < currentLevel.getLevelHeight(); x++){
for(int y = 0; y < currentLevel.getLevelWidth(); y++){
currentLevel.getLevel().get(x).set(y, Integer.parseInt(allLines.split("\\.")[x].toString().split(";")[y]));
System.out.print(currentLevel.getLevel().get(x).get(y));
}
System.out.println("");
}
You must have initialized
level = new ArrayList<ArrayList<Integer>>();
badly. There is only one object ArrayList<Integer> and it is stored repeatedly to create the List of Lists.
I'm trying to print out an indicator of coordinates on a 2D array...
There is another class that I've used to instantiate objects on the array.
I need to the store coordinates in two (local?) variables, and then display the position of those coordinates in the printed array. (that has already been instantiated with various objects)
This is a snippet of code I have so far, but I can't get the 'C' to print in the right spot on the array. The few options that I tired, either doesn't print it at all, or prints the 'C' in the top left hand corner.
This is one option that I've tired: This option doesn't print the 'C' at all.
private int cX=0;
private int cY=0;
//Randomly set coordinates on array.
for(int i=0; i<array.length; i++){
for(int j=0; j<array[i].length; j++){
int x = randGen.nextInt(9);
int y = randGen.nextInt(9);
if (array [x][y].display()=='.'){
x=cX;
y=cY;
}
}
}
// print array
private void displayArray()
{
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
if ((array [i][j].display()==cX)&&
(array [i][j].display()==cY))
System.out.print("C");
System.out.print(board [i][j].display()+"\t")
}
System.out.println("\n");
}
}
If I understood you right, you'd like to save coordinates to some kind of data structure and later display them?
Wouldn't it be suitable to create a class for this purpose? E.g.
A class called Coordinator, that holds the X & Y values.
Later create a object of the class you've made with X & Y values and put it to a ArrayList.
Code Example:
//Creating the a object holding 2 values
Coordinator cords = new Coordinator(randGen.nextInt(9), randGen.nextInt(9));
//Putting in the object to the data structure
List<Coordinator> list = new ArrayList<>();
list.add(cords);
The explanation and code example should help you solve this issue on your own hopefully.
This option doesn't print the 'C' at all.
Your current code example will indeed never print a 'C'.
for (int j = 0; j < array[i].length; j++){
if ((array [i][j].display()==cX)&&
(array [i][j].display()==cY))
This if condition will be true only if cX equals cY and both are equal to the ascii code value assigned to the array (for '.' this is the value 46). But you may just want to find the cX,cY position and print a 'C'. You should try to campare your position (cX, cY) with the current i and j values.
if ((i==cX)&&(j==cY))
prints the 'C' in the top left hand corner
You never change the content of array at the position. You set x and y which will be overwritten and are later no accessible
int x = randGen.nextInt(9);
int y = randGen.nextInt(9);
if (array [x][y].display()=='.'){
x=cX;
y=cY;
}
Do you want to find a random position for your 'C' to appear, like in a board game?
Then you need to assign your found x and y coordinate to cX and cY. The right value gets assigned to the left variable.
cX = x;
cY = y;
I hope I understood you right and this helps.
For completeness: I think I worked it out. (Well it seems to be working anyway).
Thanks for the help!
private int cX=0;
private int cY=0;
//Randomly set coordinates on the array.
for(int i=0; i<1; i++){
int x = randGen.nextInt(9);
int y = randGen.nextInt(9);
if (board [x][y].display()=='.'){
CX=x;
CY=y;
}
}
//Print array
private void displayArray(){
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board[i].length; j++){
if ((i==CX)&&(j==CY))
System.out.print("C"+"\t");
else
System.out.print(board [i][j].display()+"\t");
}
System.out.println("\n");
}
}
private double[][] mLatLng = {
{19.01062463, 73.01141475},
{19.02369039, 73.00778391},};
public void onMapReady(GoogleMap googleMap) { googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_icon);
for (int i = 0; i < mLatLng.length; i++) {
for (int j = 0; j < mLatLng[i].length; j++) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(mLatLng[i][j], mLatLng[i][j]))
.title("Location" + i).icon(bitmapDescriptorFromVector(context,R.drawable.ic_icon)));