Understanding Iteration with 2d arrays Java - java

I am watching a tutorial on 2d arrays and I can't seem to understand where the values for
states.length and states[i].length are coming from. How does it know the outer loop deals with the size 3 array and the inner is the size 2 array?
public class Test3 {
public static void main(String[] args) {
String [][] states = new String[3][2];
states[0][0] = "California";
states[0][1] = "Sacremento";
states[1][0] = "Oregon";
states[1][1] = "Salem";
states[2][0] = "Washington";
states[2][1] = "Olympia";
for (int i = 0; i < states.length; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < states[i].length; j++) {
sb.append(states[i][j]);
}
System.out.println(sb);
}
}
}

The states.length is the row length of your array while the states[i].length is the number of column of the specified row.

Well, a two dimensional array is an array of arrays.
So String[3][2] is
[["string", "string"],
["string", "string"],
["string", "string"]]
states.length is the length of the outer array, which is 3.
states[i].length is the length of each individual array, which are all 2.

You begin by creating a 2D array that looks like the following.
[[California, Sacramento]
[Oregon, Salem]
[Washington, Olympia]]
The first for loop will iterate over each row. In this case states.length is 3 because there are 3 rows.
The next for loop will iterate over the columns in each row.
In other words, states[i] will give you a row. If i is 0, then states[0] is [California, Sacramento]
There are 2 entries in that row, so states[0].length is 2.

Related

find number of columns in a 2D array Java

I'm new to java and am trying to find the transpose of a matrix X with m rows and x columns. I'm not familiar with java syntax but I think I can access the number of rows using double[x.length] but how do I figure out the number of columns? Here is my code:
import stdlib.StdArrayIO;
public class Transpose {
// Entry point
public static void main(String[] args) {
double[][] x = StdArrayIO.readDouble2D();
StdArrayIO.print(transpose(x));
}
// Returns a new matrix that is the transpose of x.
private static double[][] transpose(double[][] x) {
// Create a new 2D matrix t (for transpose) with dimensions n x m, where m x n are the
// dimensions of x.
double[][] t = new double[x.length][x[1.length]]
// For each 0 <= i < m and 0 <= j < n, set t[j][i] to x[i][j].
// Return t.
}
}
Also, I was trying to figure it out by printing a 2D list in a scrap file but It wouldn't work for some reason, where is what I had:
import stdlib.StdArrayIO;
import stdlib.StdOut;
public class scrap {
public static void main(String[] args){
double[][] x = new double[10][20];
StdOut.println(x.length);
}
}
Could you point out what I was doing wrong? It kept waiting on input. I could also use any other tips that would help, I am transitioning from Python.
In Java, a two-dimensional array is merely an array of arrays. This means the length of any of the array elements can be checked to find the number of columns. Using your example, this would be:
double[][] t = new double[x[0].length][x.length];
This should be sufficient for your matrix situation, where we can assume the outer array is not empty, and all inner arrays have the same length.
Note that this is not guaranteed to work in general. If the outer array is empty, there are no inner arrays to check, so the number of columns isn't defined and can't be determined. Secondly, there is no guarantee that all inner arrays of a given array of arrays in Java are all the same length. They will be using the new double[x][y] syntax, but the array could have been created using another mechanism or one of the inner arrays could have been replaced with an array of a different length.
class TwoDmArray {
public static void main(String[] args) {
int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 } };
for(int i = 0; i < 2; i++) { // It represents row
for(int j = 0; j < 3; j++) { // It represents column
System.out.print(arr[i][j]);
if(j == 2) { // When column index will be 2 then will print elements in new line
System.out.println();
}
}
}
}
}
OUTPUT : 123
456
Explanation : Here array has 2 rows and 3 columns so, matrix will be in row and column form.

Inputting values to a full 2d array

I'm currently trying to figure out how to add values into a full 2d array. Any help would be appreciated.
This is what i currently have.
public static ObjectA[][] addValue(ObjectA value, ObjectA[][] oldArray)
{
//Creates a new array with an extra row
ObjectA[][] newArray = new ObjectA[oldArray.length +1][oldArray[0].length]
for (int i= 0 ; i < newArray.length; i++)
{
for (int ii = 0; ii <= newArray[0].length; ii++)
{
// when the index exceeds the oldArray
// it will add the value to the newArray
if (i <= oldArray.length)
{
newArray[i][ii] = oldArray[i][ii];//copies all values into newArray
}
else
{
newArray[i][ii] = value; //adds value to the last row
}
}
}
return newArray;
}
What I currently have done is input a value to the new row however the method is going to be called multiple times to add more than one value. Which mean it's going to create multiple rows rather than adding to the next available column.
EDIT:
mistyped the data type the array and value are suppoed to be objects.
First, your code throws an IndexOutOfBoundsException. Here is why:
Consider the if (i <= oldArray.length) clause. Say, oldArray.length is 3. When i = 3, newArray[i][ii] = oldArray[i][ii] line seeks the oldArray[3][ii] elements but there are no such elements. All the possible elements of oldArray is oldArray[0][ii], oldArray[1][ii] and oldArray[2][ii], since counting starts with 0 in programming.
Second, I didn't get the point of adding another row for each next value. If you're not going to add a set of values to each row, then, why do you consider expanding number of rows?
This is a typical situation when you need to make a tradeoff between element access complexity and complexity of adding new column
If you need fast column adding without new structure allocation you should use LinkedList as a storage of rows and call list.add(row) every time you need to add a new column so your code will look like:
public static void addValue(int value, LinkedList<int[]> list) {
int[] row_you_need_to_add = new int[list.get(0).length];
for (int i = 0; i < list.get(0).length; i++) {
row_you_need_to_add[i] = value;
}
list.add(row_you_need_to_add);
}
As 2D Array is an Array which consist of an array within an Array. So at every index of 2D array there is another array is present and has a specific size.
public static ObjectA[][] addValue(ObjectA value, ObjectA[][] oldArray) {
ObjectA[][] newArray = new ObjectA[oldArray.length +1][oldArray[0].length]
for (int i= 0 ; i < newArray.length; i++) {
for (int ii = 0; ii <= newArray[0].length; ii++) {
// when the index exceeds the oldArray
// it will add the value to the newArray
if (i <= oldArray.length) {
newArray[i][ii] = oldArray[i][ii];//copies all values into newArray
} else {
newArray[i][ii] = value; //adds value to the last row
}
}
}
return newArray;
}

How can I create a two-dimensional array containing ArrayLists?

How can I create a two-dimensional array containing ArrayLists? Something like this :
ArrayList<Character>[][] myArray = new ArrayList<Character>[][];
and would it be ok to do the following :
I need to compare the position of some characters with the position of the buildings in my map. Several buildings can belong to the same tile, but one can be drawn in front of the character and the other behind him. This comparison has to be done all the time in the game, with every character.
I am trying to update an array of characters each time a character is moving from one tile to another. Then the render method should look for how many characters, if any, are in a specific tile, and loop over the characters in this tile to draw them in front or behind the buildings.
Something like this :
//init
ArrayList<Character>[][] arrayOfCharacters = new ArrayList<Character>[][];
//each tile in the map
for (int y = 0; y < 9; y++){
for(int x = 9-1; x >= 0; x--){
if ( arrayOfCharacters[y][x].length > 0 ){
for ( int i=0, i< arrayOfCharacters[y][x].length; i++ ){
//compare which building is in front or behind the characters
//then
characterInThisTile = index of each character in arrayOfCharacters[y][x]
spriteBatch.draw(characterInThisTile, x_pos, y_pos, tileWidth, tileHeight);
}
}
}
}
ArrayList<Character>[][] arrayOfCharacters = new ArrayList[9][9];
for(int i=0;i<arrayOfCharacters.length;i++){
for(int i2=0;i2<arrayOfCharacters[i].length;i2++){
arrayOfCharacters[i][i2]=new ArrayList<Character>(20);
}
}
A two dimensional array is an array of arrays - it means that the structure looks something like:
[0,0][0,1][0,2][0,3] -> sub array 1
[1,0][1,1][1,2] -> sub array 2
[2,0][2,1][2,2][2,3][2,4] - sub array 3
Notice how the number of elements in each sub array does not have to be the same. You could create the above array as (I am using integers your type would vary as necessary):
int[][] a = new int[3][]; // The number of sub arrays or the first argument should be defined.
// The number of elements in each sub array need not be known at compile time though
So if had to do the same thing with an ArrayList, an array inside an array would translate to a list within a list. So you could do something like:
ArrayList<ArrayList<Integer>> arrayList = new ArrayList<ArrayList<Integer>>();
Since an ArrayList object can expand dynamically, the structure would be something like:
Row [0] -> [0][1][2]..... // and so on
Row [1] -> [0][1][2]..... // and so on
Row [2] -> [0][1][2]..... // and so on
Entering elements into this would be done very similarly using nested for loops.
You could make a class and then make Objects using that class that stores an ArrayList<Character> as an instance variable.
First make a class that has a instance variable ArrayList<Character>
that also has a getter, setter and constructor.
//Make Objects that will have an ArrayList<Character>
public class ArrayOfChars {
private ArrayList<Character> list;
//Constructor
public arrayOfChars(){
this.list = new ArrayList<Character>();
}
//Getter
public ArrayList<Character> getList(){
return this.list;
}
//Setter
public void setList(ArrayList<Character> list){
this.list = list;
}
}
You can now use this class to make Objects and store that Objects in a 2D array
These Objects can store and ArrayList<Character> that can be used.
public static void main(String[] args) {
ArrayOfChars[][] myLists = new ArrayOfChars[9][9];
//initialize the 2d array so that it is filled with Empty ArrayList<>'s'
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
ArrayOfChars thislist = new ArrayOfChars();
myLists[i][j] = thislist;
}
}
//You can now use it like a 2d array of objects
Here are some ways you can use this 2D-Array of ArrayList<Character>
//Iterate like this
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
myLists[row][col].getList().get(index);
//or
myLists[row][col].setList(list);
}
}
//Add to a list
myLists[2][5].getList().add(new Character('H'));
//Set a list of characters
ArrayList<Character> useThisList = new ArrayList<Character>();
useThisList.add('F');
useThisList.add('G');
useThisList.add('L');
myLists[3][7].setList(useThisList);
}
I'd use list of lists, which is more dynamic.
List<ArrayList<Character>> list =
new ArrayList<ArrayList<Character>>();

2d char array from a file

I am trying to read in a string from a file, extract individual characters and use those characters to fill a 2D char array. So far I have been able to do everything except fill the array. I keep getting an Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: error message. Any help would be appreciated. This is my first time working with 2D arrays. Thanks.
Here are the contents of the test.txt. Each word on a new line. The first 2 integers are the dimensions of the array
4 4
FILE
WITH
SOME
INFO
public class acsiiArt
{
public static void main(String[] args) throws IOException
{
File file = new File("test.txt");
Scanner inputFile = new Scanner(file);
int x = inputFile.nextInt();
int y = inputFile.nextInt();
while (inputFile.hasNext())
{
char [][] array = new char [x][y];
//char c = words.charAt(i);
for (int row =0; row<x;row++)
{
for (int col =0; col<y;col++)
{
String words = inputFile.nextLine();
for (int i=0; i<words.length(); i++)
array[x][y]=words.charAt(i);
}
}
}
}
}
for (int row =0; row<x;row++)
{
for (int col =0; col<y;col++)
{
String words = inputFile.nextLine();
for (int i=0; i<words.length(); i++)
array[x][y]=words.charAt(i);
}
}
The total number of indices in array is x * y. Below, you are filling all the possible indices
for (int row =0; row<x;row++)
{
for (int col =0; col<y;col++)
So when you add this:
for (int i=0; i<words.length(); i++)
you multiplying another factor words.length. So you need x * y * words.length number of indices, but you only have x * y. Thats why you're getting ArrayIndexOutOfBoudsException
I've seen problems like this and I'm assuming that x and y are being initialized to the first two characters which represent the number of rows and the number of columns. If that is the case, then third for loop for (int i=0; i<words.length(); i++) is unnecessary. You can just reffer to the col variable for the word at that point, since it should represent how many characters there are.
All of this is only applicable if the chars are in a rectangular pattern, meaning that there are the same number of columns in every row. Otherwise you will get an IndexOutOfBoundsError as soon as one of the lines is shorter than the the column value initially given.
Edit: If you're final 2d char array is not meant to be rectangular and instead "jagged," a different implementation is required. I'd recommend either a 2d arrayList (an arrayList of arrayLists).
Or you can keep your current implementation with the third for loop, but you have to be sure that the original x value represents the longest row/most amount of columns, and then you'd be able to deal with each row indivually with words.length. You'd also have to be fine with the extra portions of the lines that have a length>x having spaces initialized to null.
ArrayIndexOutOfBoundsException means you are using array beyond its limit. So in your case:
char [][] array = new char [x][y];
//char c = words.charAt(i);
for (int row =0; row<x;row++) {
for (int col =0; col<y;col++){
String words = inputFile.nextLine();
for (int i=0; i<words.length(); i++)
array[x][y]=words.charAt(i);
}
}
Problem may be because your array size is less then input words. problem is because you are putting extra loop, and your loop it self is not correct. Please seen code below.
So you can do 2 things.
change value of y large enough so that any word string can store.
rather than looping on size of word you can loop on your array size like.
.
for (int row =0; row<x;row++) {
String words = inputFile.nextLine();
int size = Math.min(words.length(),y);
for (int i=0; i< size; i++)
array[row][i]=words.charAt(i);
}
The easiest way to do this is with an ArrayList<char[]>. All you have to do is add a new char[] for each new line read:
ArrayList<char[]> chars = new ArrayList<>();
while (inputFile.hasNext()){
chars.add(inputFile.nextLine().toCharArray());
}
char[][] array = chars.toArray(new char[chars.size()][]);
An ArrayList is basically an array of changeable size. This code takes each line in the file, turns it into a char[], then adds it to the ArrayList. At the end, it converts the ArrayList<char[]> into a char[][].
If you can't or don't want to use ArrayList, you could always do this:
char[][] array = new char[1][];
int a = 0;
while(inputFile.hasNext()){
//read line and convert to char[]; store it.
array[a] = inputFile.nextLine().toCharArray();
//if there are more lines, increment the size of the array.
if (inputFile.hasNext()){
//create a clone array of the same length.
char[][] clone = new char[array.length][];
//copy elements from the array to the clone. Note that this can be
//done by index with a for loop
System.arraycopy(array, 0, clone, 0, array.length);
//make array a new array with an extra char[]
array = new char[array.length + 1][];
//copy elements back.
System.arraycopy(clone, 0, array, 0, clone.length);
a++;
}
}
If you know the dimensions of the array beforehand:
char[][] array = new char[dimension_1][];
int a = 0;
while (inputFile.hasNext()){
array[a] = inputFile.nextLine().toCharArray();
a++; //don't need to check if we need to add a new char[]
}
In response to comment:
We know that a char[][] cannot be printed with Arrays.toString() (if we want the contents) because we will get a lot of char[].toString(). However, a char[][] can be printed with one of the following methods:
public static String toString(char[][] array){
String toReturn = "[\n";
for (char[] cArray: array){
for (char c: cArray){
toReturn += c + ",";
}
toReturn += "\n";
}
return toReturn + "]";
}
I personally prefer this one (requires import java.util.Arrays):
public static String toString(char[][] array){
String toReturn = "[\n";
for (char[] cArray: array){
toReturn += Arrays.toString(cArray) + "\n";
}
return toReturn + "]";
}

Multidimensional Arrays lengths in Java

How to find the lengths of a multidimensional array with non equal indices?
For example, I have int[][] pathList = new int[6][4]
Without actually hard-coding the indices, I need to find the '6' and the '4'.
I can find the 6 with pathList.length, but how to obtain the '4'?
This will give you the length of the array at index i
pathList[i].length
It's important to note that unlike C or C++, the length of the elements of a two-dimensional array in Java need not be equal. For example, when pathList is instantiated equal to new int[6][], it can hold 6 int [] instances, each of which can be a different length.
So when you create arrays the way you've shown in your question, you may as well do
pathList[0].length
since you know that they all have the same length. In the other cases, you need to define, specific to your application exactly what the length of the second dimension means - it might be the maximum of the lengths all the elements, or perhaps the minimum. In most cases, you'll need to iterate over all elements and read their lengths to make a decision:
for(int i = 0; i < pathList.length; i++)
{
int currLen = pathList[i].length;
}
This is for a 3 dimensional array.
int x[][][]=new int[5][8][10];
System.out.println(x.length+" "+x[1].length+" "+x[0][1].length);
OUTPUT :
5 8 10
Java has "jagged" multidimensional arrays, which means that each "row" in your two-dimensional array can have a different number of components. If you can assume that each row has the same number of components, use:
pathList[0].length;
Otherwise, you will have to iterate:
int maxRowLength = 0;
for (int i = 0; i < pathList.length; i++) {
if (maxRowLength < pathList[i].length) {
maxRowLength = pathList[i].length;
}
}
For 2 D array :-
int x[][] = new int[6][12];
System.out.println(x.length + " " + x[1].length);
OUTPUT : 6 12
pathList.length gives you the number of rows. This means it will output 6 for int[6][4]
pathList[i].length gives you the number of columns in the ith row. Since int[6][4] can be seen as a rectangle it will always output 4.
In java we can define array of arrays which we call multi dimensional arrays.By array of arrays we mean that a single elment of our array is again an array (in java can be of multiple length).To find length of multi array having all subarray of same size,we can use:
int[][]a=new int[3][3];//let a[][] be my array
a.length will work. //a is an object of proxy class and length is its property.
However,if you have subarrays of different sizes then you have to iterate it.
for(i=0;i<a.length;i++)
int cur_size=a[i].length;
In Java we can't use Length field like we used to one-dimensional arrays.
So simply writing a few lines of code solves this problem.
First, you need to know that the output of the Length field in multidimensional arrays is the number of rows.I mean when you have below array
int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
the result of
System.out.println(numbers.length);
is 2, because you have 2 rows. So, you should use this to solve this problem.
Example:
public class Main {
public static void main(String[] args) {
//Array definition
int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
//Number of array's elements
int result = 0;
//calculate via loop
for(int i=0; i< numbers.length; i++){
result += numbers[i].length;
}
//output
System.out.println(result);
}
}
You can find '4' by using pathlist[i].length
Please rectify me if I am wrong as I am a novice and would help me in understanding Java better. The following code may help you in understanding.
public class Main {
public static void main(String[] args) {
int num[][] = new int[1][3];
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length; j++) {
num[i][j] = 10;
System.out.println("num [" + i + "] [" + j + "] = " + num[i][j]);
}
}
}
}
3-D array length
int[][][] a = new int[2][3][7];
int length=0;
for(int[][] i:a){
for(int j[]:i){
length+=j.length;
}
}
System.out.println(length);

Categories

Resources