How should I understand a "for" statement in a tilemap? - java

I'm following a tutorial online and I'm having troubles understanding the code which is written there.
public Tilemap() {
int[][] tilemap = new int[30][50];
System.out.println("New Tilemap created.");
Random r = new Random();
int rows = tilemap.length;
int columns = tilemap[1].length;
printTiles(rows, columns, tilemap, r);
}
public void printTiles(int rows, int columns, int[][] tilemap, Random r) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
tilemap[i][j] = r.nextInt(5);
System.out.print(" " + tilemap[i][j]);
}
System.out.println(" ");
}
}
I understand everything up until the for statement:
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
tilemap[i][j] = r.nextInt(5);
System.out.print(" " + tilemap[i][j]);
}
System.out.println(" ");
}
The tutorial doesn't explain one bit about them. So if anyone could help me understand, what is the purpose of most of the lines in the for statement, I'd appreciate that.

It looks like it's iterating through the entire 2D array and placing random integers at every index.
I've commented the code below. Hopefully this explains it.
for (int i = 0; i < rows; i++) { //iterate through every row
for (int j = 0; j < columns; j++) { //iterate through every column
tilemap[i][j] = r.nextInt(5); //place an integer between 0 (inclusive) and 5 (exclusive) at the specified location in the 2d array
System.out.print(" " + tilemap[i][j]); //print the integer that was just placed with a preceding space
}
System.out.println(" "); //print a new line since we've reached the end of the row
}

Related

Is there a way to fix my two dimensional array problem

How can I find the total sum for each two dimensional array row? I'm completely stuck...
public static void main(String[] args) {
int [][] grid = new int [10][10];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = (int)(Math.random()*99);
}
}
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
System.out.print("1.");
System.out.printf("%5d ", grid[i][j]);
}
System.out.println();
}
}
My current output is:
How can I show the total sum for each row in the end of the row and show column numbers
For the sum of a row, this should do. In a similar way within the i loop, if you need to count the column as well;
for(int i = 0; i < 10; i++) {
int jSum = 0;
for(int j = 0; j < 10; j++) {
jSum += grid[i][j];
System.out.print("1.");
System.out.printf("%5d ", grid[i][j]);
}
System.out.printf(" %5d", jSum);
System.out.println();
}
On the column numbering:
Either you just pust put a static print in the beginning (like print "1 2 3 4..."), or you put the following with the j loop:
if (i == 0) System.out.printf("%5d ", j); // only prints in first loop / row - print 1,2,3,4,5....

indexoutofbound error when shifting 2D array elements java

public static int[][] shift(final int[][] original, final int amount) {
int[][] shifted = new int[original.length][original[0].length];
for (int col = 0; col < original.length; col++) {
for (int row = 0; row < original[col].length; row++) {
shifted[col][row] = FILL_VALUE;
}
for (int cols = 0; cols < original.length + amount; cols++) {
for (int rows = 0; rows < original[cols].length; rows++) {
if (cols - amount < original.length) {
shifted[cols][rows] = original[cols - amount][rows];
}
}
}
}
return shifted;
}
Hi,
I am trying to write a method that will shift the elements in my 2-D array to the left by some arbitrary amount. I don't want to loop the values back around, but instead fill the empty arrays with some fill_value which is already predefined. And if the shift amount is more than the orignial length, I would just return an image with only fill_value. However, this function is throwing an arrayindexoutofbound Error. But I can't think of how I should change my for loop to fix the error. Any help is appreciated! Thank you!
I believe it's because in your second outer for loop, the condition is cols < length + amount, so it will continue past the edge of the array if amount > 0. You could step through your code with a debugger and see exactly where it's going out of bounds.
The error is occurring because of following line:
shifted[cols][rows] = original[cols - amount][rows];
When cols=0, rows=0, amount=2 (say), it is trying to access original[-2][0] which does not exist.
Instead you may use following:
public class overflow1 {
static int a[][] = {{1,2,3,4,5,6},{2,3,4,5,6,7},{3,4,5,6,7,8}, {4,5,6,7,8,9}, {5,6,7,8,9,10}, {6,7,8,9,10,11}};
static int b[][] ;
static int FILL_VALUE =0;
public static int[][] shift(final int[][] original, final int amount) {
int[][] shifted = new int[original.length][original[0].length];
for (int col = 0; col < original.length; col++) {
for (int row = 0; row < original[col].length; row++) {
shifted[col][row] = FILL_VALUE;
}
for (int cols = 0; cols < original.length ; cols++) {
for (int rows = 0; rows < original[cols].length; rows++) {
if (cols - amount >=0) {
shifted[cols][rows] = original[cols - amount][rows];
}
}
}
}
return shifted;
}
public static void main(String[] arggs) {
b=shift(a,2);
System.out.println("Original array:");
for(int i=0; i<a.length; i++){
for (int j=0; j<a[i].length; j++){
System.out.print(a[i][j]+ ":");
}
System.out.println();
}
System.out.println("After shift by 2 array:");
for(int i=0; i<b.length; i++){
for (int j=0; j<b[i].length; j++){
System.out.print(b[i][j]+ ":");
}
System.out.println();
}
}
}
Here is the output for the sample:
Original array:
1:2:3:4:5:6:
2:3:4:5:6:7:
3:4:5:6:7:8:
4:5:6:7:8:9:
5:6:7:8:9:10:
6:7:8:9:10:11:
After shift by 2, array:
0:0:0:0:0:0:
0:0:0:0:0:0:
1:2:3:4:5:6:
2:3:4:5:6:7:
3:4:5:6:7:8:
4:5:6:7:8:9:

How to create two dimensional grid with two-d. array?

This is my current code:
public static void main(String[] args) {
int [][] twoD = new int [5][5];
/*for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j] + "");
}
}*/
}
}
I can't seem to do it. I got confused and I removed the part of testing w/commenting. Just ignore that.
I am aiming to get a two dimensional array like this:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
However, I just don't get it. How can I get that result? I'm a beginner at java.
First, you need to populate the array with data, and you forgot System.out.println for each row of the array.
int [][] twoD = new int [5][5];
// populate array with data
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
twoD[i][j] = (j+1)*(i+1);
}
}
// print result
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j]);
System.out.print(" ");
}
System.out.println();
}
You have to populate the data as well:
int[][] arr = new int [5][5];
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
arr[i][j] = (j+1)*(i+1);
}
}
And the code to print would be:
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
You are doing fine, you just need to put line jump System.out.println(); every time the second for ends
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
You are on the right track, that for loop will print out the array like that, all you need to do is print a new line character after finishing the for(j) loop. But, at least in the snippet you posted, you aren't actually doing any assignments, so there aren't any values in your array to print, Java will initialize all ints to zero for you.
The array doesn't just automatically populate with incrementing integers, rather each cell of the array will automatically initialized to 0, you have to set the values you want the array to contain. You can use the concept of your testing class to do this if you wish, just set each cell of the 2D array to a certain value. After that, you can print out the array, making sure to print a each row of the array on a new line. For instance:
public static void main(String[] args) {
int [][] twoD = new int [5][5];
int increment = 1;
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
twoD[i][j] = increment++;
}
}
for(i = 0; i<5; i++){
for(j = 0; j<5; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
The first set of nested for loops will set each of the cells of the 2D array to the incremented integers you want (note increment++ will first set the cell to the value increment currently is, then add one to the variable). The second set of nested for loops will print out the array as you desire.
refer this code
int[][] twoD = new int[5][5];
// add values to array
for (int i = 0; i < 5; i++) {
int val = 1;
val = val + i;
for (int j = 0; j < 5; j++) {
twoD[i][j] = val * (j + 1);;
}
}
// Print array
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
as others pointed out you need to print it nicely to see the pattern, i and j are indices of your array. However, I see that you have a nice pattern so just running two loops won't solve the problem.
Maybe something like this would help (not giving exact answer intentionally)
int [][] twoD = new int [5][5];
int i;
// initialize
int c = 1; int j = 0;
for(c=1; c<5; c++) {
for( i = 1; i<=5; i++){
twoD[i-1][c-1] = c*c*i; twoD[c-1][i-1]=c*c*i;
}
}
for( i = 0; i<5; i++) {
for( j = 0; j<5; j++) {
System.out.print(twoD[i][j]);System.out.print(" " );
}
System.out.println("\n");
}

Adding Elements of an Array (sum of rows and columns)

I'm looking for a way to add up the elements of the rows of an array and get that sum. I have to get the column's sum as well.
The array looks something like this:
{{45.24, 54.67, 32.55, 25.61},
{65.29, 49.75, 32.08, 26.11},
{25.24, 54.33, 34.55, 28.16}};
For example, I would add 45.24, 65.29, and 25.24 to get the sum of that part of the columns. I would then have to add the other 3 columns up as well.
Same goes for the rows.
I keep getting errors concerning the variable types. Is there a way to do this? Thanks.
The logic Would be --->
for(i = 0; i < columns; i++)
{
for(j=0; j<rows; j++)
{
sum+=arr[j][i];
}
}
Opposite for Columns
I think you should define the type of numbers your array will handle, if I use float numbers I can have some code like the class bellow to do the type of operations you are asked for. You can also add some decimal formatting.
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
float myarray[][]= {
{45.24f, 54.67f, 32.55f, 25.61f},
{65.29f, 49.75f, 32.08f, 26.11f},
{25.24f, 54.33f, 34.55f, 28.16f}
};
float row[] = new float[3];
float column[] = new float[4];
for (int i=0; i < 3; i++) {
float rowvalue = 0f;
for (int j=0; j < 4; j++) {
System.out.print(myarray[i][j]+" ");
rowvalue+=myarray[i][j];
}
row[i]=rowvalue;
System.out.println("");
}
System.out.println("");
for (int i=0; i < 4; i++) {
float colvalue = 0f;
for (int j=0; j < 3; j++) {
System.out.print(myarray[j][i]+" ");
colvalue+=myarray[j][i];
}
column[i]=colvalue;
System.out.println("");
}
System.out.println("Rows answer:");
for (int i=0; i < 3; i++) {
System.out.println(row[i]);
}
System.out.println("Columns answer:");
for (int i=0; i < 4; i++) {
System.out.println(column[i]);
}
}
}
Suppose you have nxn matrix. The idea is to identify the pattern.
Row values
i j
0 0
0 1
0 2
Column values
i j
0 0
1 0
2 0
The position of i and j values is reversed.
Let's assume we have an array a[][]. The logic would be:
for (int i=0; i<n; i++) {
int row = 0, col = 0;
for (int j=0; j<n; j++) {
row += a[i][j];
col += a[j][i];
}
System.out.println("row" + i + " = " + row);
System.out.println("col" + i + " = " + col);
}
I assumed you wanted the sum of each row and column separately. You can modify it accordingly.

Fill double array with random numbers and then print even and odd numbers from that array

So here's my problem. I have to write a program that will fill array with random numbers(and it's ok), then it's necessary to print only even index numbers or only odd value numbers(j). Tried like this but when i put if statement and it shows every even number (index and value-the second in array) so it wrong. What should i do so?
import java.util.Random;
public class Array {
public static void main(String[] args)
{
int rows = 5;
int colu = 2;
Random r = new Random();
int [][] array = new int [rows][colu];
for(int row = 0; row < array.length; row++)
{
for(int col = 0; col < array[row].length; col++)
{
array[row][col] = r.nextInt(10);
}
}
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
if(array[i][j]%2 == 0){
System.out.print(array[i][j] + " ");
}
}
}
System.out.println();
}
}
Thanks
I'm going to take a stab at this but I'm not sure if I quite understand yet.
int array[][] = new int[row][col];
// ... populate the array with random numbers, works fine...
// Let's traverse the first column.
for (int i = 0; i < row; i++) {
int value = array[i][0]; // col 0 means first column
if (value % 2 == 0) {
// ...
}
}
// Let's traverse the second column.
for (int i = 0; i < row; i++) {
int value = array[i][1]; // col 1 means second column
// ...
}
Is this what you mean? If it is, do you see the pattern and how you could generalize this and make the code a bit smaller?
Just implement this formula in your "if" statement :
(Number × 2 )/4 ==0. You will always get even numbers. You can handle the rest :D

Categories