How do I get the second dimension of an array if I don't know it? array.length gives only the first dimension.
For example, in
public class B {
public static void main(String [] main){
int [] [] nir = new int [2] [3];
System.out.println(nir.length);
}
}
See that code run live at Ideone.com.
2
How would I get the value of the second dimension of nir, which is 3?
which 3?
You've created a multi-dimentional array. nir is an array of int arrays; you've got two arrays of length three.
System.out.println(nir[0].length);
would give you the length of your first array.
Also worth noting is that you don't have to initialize a multi-dimensional array as you did, which means all the arrays don't have to be the same length (or exist at all).
int nir[][] = new int[5][];
nir[0] = new int[5];
nir[1] = new int[3];
System.out.println(nir[0].length); // 5
System.out.println(nir[1].length); // 3
System.out.println(nir[2].length); // Null pointer exception
In the latest version of JAVA this is how you do it:
nir.length //is the first dimension
nir[0].length //is the second dimension
You can do :
System.out.println(nir[0].length);
But be aware that there's no real two-dimensional array in Java. Each "first level" array contains another array. Each of these arrays can be of different sizes. nir[0].length isn't necessarily the same size as nir[1].length.
use
System.out.print( nir[0].length);
look at this for loop which print the content of the 2 dimension array
the second loop iterate over the column in each row
for(int row =0 ; row < ntr.length; ++row)
for(int column =0; column<ntr[row].length;++column)
System.out.print(ntr[row][column]);
int secondDimensionSize = nir[0].length;
Each element of the first dimension is actually another array with the length of the second dimension.
Here's a complete solution to how to enumerate elements in a jagged two-dimensional array (with 3 rows and 3 to 5 columns):
String row = "";
int[][] myArray = {{11, 12, 13}, {14, 15, 16, 17}, {18, 19, 20, 21, 22}};
for (int i=0; i<myArray.length; i++) {
row+="\n";
for (int j = 0; j<myArray[i].length; j++) {
row += myArray[i][j] + " ";
}
}
JOptionPane.showMessageDialog(null, "myArray contains:" + row);
nir[0].length
Note 0: You have to have minimum one array in your array.
Note 1: Not all sub-arrays are not necessary the same length.
Assuming that the length is same for each array in the second dimension, you can use
public class B {
public static void main(String [] main){
int [] [] nir= new int [2] [3];
System.out.println(nir[0].length);
}
}
Remember, 2D array is not a 2D array in real sense.Every element of an array in itself is an array, not necessarily of the same size.
so, nir[0].length may or may not be equal to nir[1].length or nir[2]length.
Hope that helps..:)
Expansion for multi-dimension array total length,
Generally for your case, since the shape of the 2D array is "squared".
int length = nir.length * nir[0].length;
However, for 2D array, each row may not have the exact same number of elements.
Therefore we need to traverse through each row, add number of elements up.
int length = 0;
for ( int lvl = 0; lvl < _levels.length; lvl++ )
{
length += _levels[ lvl ].length;
}
If N-D array, which means we need N-1 for loop to get each row's size.
//initializing few values
int[][] tab = new int[][]{
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1}
};
//tab.length in first loop
for (int row = 0; row < tab.length; row++)
{
//tab[0].length in second loop
for (int column = 0; column < tab[0].length; column++)
{
//printing one value from array with space
System.out.print(tab[row][column]+ " ");
}
System.out.println(); // new row = new enter
}
Related
I have a method which is intended to slice one bigger Array into a few smaller arrays. I would like it to return these arrays as an two dimensional array. So far slicing works but I have no idea how to write arr2[] elements to slice[][]. The problem is count of arrays slice[?][i] is unknown.
private short[][] slice(short array1[], int sliceSize) {
short arr2[]=null;
short slice[][]=null;
for (int offset = 0; offset < array1.length ; offset+=sliceSize) {
arr2 = Arrays.copyOfRange(array1, offset, offset+sliceSize);
for(int i=0; i<arr2.length; i++) {
System.out.print("\n value: "+ String.valueOf(arr2[i]));
// slice[?][i]=arr2[i];
}
}
return slice;
}
You can easily know the number of slice you need from the orignal array length.
int sliceCount = arr1.length / sliceSize + 1;
short[][] slice = new short[sliceCount][];
Note that we would end up with one to many cell if the length is a multiple of the slice size, we can simply substract 1 to arr1.length to correct that (didn't do it to keep the code simple)
Then, you just need to do some copy just like you do and store the result in it.
Since Arrays.copyOfRange return a new array instance each call, you can store the instance directly instead of iterating the array.
for (int i = 0; i < sliceCount; i++) {
arr2 = Arrays.copyOfRange(array1, i * sliceSize, ( i + 1 ) * sliceSize);
slice[i] = arr2;
}
return slice;
Example :
[1,2,3,4,5,6,7,8,9] into slice of 4 length
-> [
[1,2,3,4],
[5,6,7,8],
[9,0,0,0]
]
Right, so I have a 2 part sorting algorithm. It's all based on an array of 14 random integers. For example:
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
Now, the first thing I'm trying to figure out how to do is to count how many a certain number exists in the original array. So, we know that 1 exists once, and 2 exists four times in the original array. But as easy as it is to visually see this, what if we don't have access to the original array. So I need to craft a method that will count how many of each number 1-9 exists and put this in a new array called count. So that index 0 in count would represent the integer 1 and would have a value of 1. Index 1 will represent the integer 2 and have a value of 4. And so on and so forth. Here is what I've got so far but I'm stuck. Sorting is pretty challenging for me.
public static void main(String[] args)
{
// int[] countFinal = {1,4,1,2,1,0,1,2,2}; // The number of times a number 1-9 appears in a[].
// int[] sortedFinal = {1,2,2,2,2,3,4,4,5,7,8,8,9,9}; // What we need as a final product.
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
//int[] count = {};
int[] sorted = {};
countHowMany(a, 1);
countHowMany(a, 2);
countHowMany(a, 3);
countHowMany(a, 4);
countHowMany(a, 5);
countHowMany(a, 6);
countHowMany(a, 7);
countHowMany(a, 8);
countHowMany(a, 9);
}
public static int countHowMany(int[] array, int value)
{
// Gathering a count for how many times a number 1-9 exists and adding it to count[];
int howManyCount = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] == value)
{
howManyCount++;
}
}
System.out.println(howManyCount);
count = new int[9];
count[howManyCount];
System.out.println(Arrays.toString(count); // Testing the input
return howManyCount;
}
It appears to count the number of times an item in the array exists properly. Now I just gotta figure out how I can add that value into a new array count[] and do it for each countHowMany(). This is the part I'm stuck on.
Once I have figured out count[] I can use it to create sorted[]. Now what sorted is supposed to do is take the data from the original array and count[] and create a new array that sorts it in ascending order and allows duplicates. So, since 1 occurs once and 2 occurs four times, the new array would be sorted[] = {1, 2, 2, 2, 2, ...}
It's a relatively small program and a small amount of integers, so it's ok that I create array's as necessary. The key being that I'm limited to using arrays and cannot use say ArrayLists for this.
You don't need to count each value individually. You can just iterate through the entire array and increment your counters for each element as you encounter it.
int counts = new int[20]; // Choose a value that's bigger than anything in your array.
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
for (int value : a) {
counts[value]++;
}
If you don't know what the largest value in your array is likely to be, you're better to use either a Map to store the counts, or some kind of List that you increase the size of as needed.
You're better off just going through the array once and incrementing a counter for each value that might appear:
int counts[] = new int[10];
for (int n: array)
counts[n]++;
That's enough to put the count for each n in counts[n]. You can then read the values out of your count[] array.
You might not have come across this syntax for a for loop over an array, by the way. It's equivalent to
int counts[] = new int[10];
for (int i=0; i<array.length; i++) {
int n = array[i];
counts[n]++;
}
but it's less verbose.
Your method may as well be void, since you're not doing anything with the returned values of your countHowMany function. This will accomplish what you want:
public static void main(String[] args)
{
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
//count the instances of each number in the array
int[] count = new int[9];
for(int i = 0; i < count.length; i++)
count[i] = countHowMany(a, i+1);
//put the values in the sorted array
int[] sorted = new int[a.length];
int position = 0; // stores the place in the array to put the new digit
for(int digit = 0; digit < 9; digit++)
{
for(int inst = 0; inst < count[digit]; inst++)
{
sorted[position] = digit + 1;
position++;
}
}
System.out.println(Arrays.toString(sorted));
}
The issue with your code is that you were trying to create the count array in each call of the countHowMany method, but this array is destroyed once the method finishes. The method calls should just return the counts, and then those returns should be put into the count array from outside the method. Note, however, that there are other ways to count the number of instances of each value, as noted by other answers.
I'm trying to create a method that takes a one dimensional array and prints it out as a two dimensional array, but as square as possible so it looks nice. I've tried creating for loops to do this, but how would you figure out how many rows and columns there are? Could someone give me the logic in how to make one, so I can use that to create my own? An explanation would be lovely.
This will make a new array that is square and big enough to house all the elements of the old array. It takes the square root of the original array's length and rounds up.
int size = (int)Math.ceil(Math.sqrt(oldArray.length));
int[][]newArray = new int[size][size];
This method will print the elements in your one-dimensional array as close as possible to a square pattern on the console output. It places tabs in between elements to line them up on each row.
private void printMyArray(String[] onDimensionalArray) {
int cols = (int) Math.floor(Math.sqrt(onDimensionalArray.length));
int currentCol = 0;
for(String element : onDimensionalArray) {
System.out.print(element + "\t");
if(currentCol >= cols) {
System.out.println("");
currentCol = 0;
}
else {
currentCol++;
}
}
}
Example:
array = |1 2 3|
|4 5 6|
|7 8 9| (3*3)
Make a 1D array
int array1 = new int[3*3];
Or you can get length of the array
For row length: int row = array.length;
For column length: int column = array[0].length;
and then int array1 = new int[row*column];
Now iterate over array and copy all elements of array into array1.
_________________
array1 = |1|2|3|4|5|6|7|8|9|
Now don't ask me for code.
check this out
int array2d[][] = new int[10][3];
for(int i=0; i<10;i++)
for(int j=0;j<3;j++)
array2d[i][j] = array1d[(j*10) + i];
I'm having difficulty understand how to write this array. I need it to out-print 10x5 (50 elements total), and have the first 25 elements equal to the sqrt of the index that it is in, and the last 25 to equal 3 * the index. Yes, this is homework but I'm not asking for you to do it for me, I just need help! I'm getting errors when using Math saying that I cant use double and the double array together. Here is what I have so far:
public class snhu4 {
public static void main(String args[]) {
double alpha[][] = new double[10][5];
double[] sum, sum2;
for (int count=0; count<=25;count++) {
alpha[count]= Math.sqrt(count);
}
for (int count=26; count<=50;count++) {
alpha[count]= count *3;
}
for (int count=0; count<=50;count++) {
System.out.print(alpha[count]);
}
}
}
Because alpha is a multidimensional array, you can't refer to its elements like a normal array.
int myarray[][] = new int[2][2];
In the above example, the array myarray is multidimensional. If I wanted to access the second element in the first array, I would access it like this:
int myint = myarray[0][1];
You are trying to access a multidimensional array by using the access for a normal array. Change
alpha[count]
to
alpha[0][count]
or similar.
Read here for more information on multidimensional arrays.
you defined alpha as a 2D array with lets say 10 items in the first dimension and 5 in the second, and 5x10 is 50 elements.
When using your array to assign values to these elements, u must call upon the array using 2 indices, one for each dimension:
alpha[i][j] = /*double value*/; //with 0<=i<=9 and 0<=j<=4
So the first 25 elements going from left to right in dimension order is going to be:
[0to9][0] and [0to9][1] and [0to4][2]
the next 25 will be
[4to9][2] and [0to9][3] and [0to9][4]
from then on i cannot give you the answers to your homework, but the loops should look like this:
int j;
for(int i = 0; i<25; i++)
{
j=i/10; //integer division will return 0 for i<10, 1 for 10<i<20, etc..
alpha[i%10][j] = Math.sqrt(i);
}
and you can figure out the rest
The 10x5 appears to be an output constraint, not a design constraint.
You are using Java, so use Java constructs, not C-language constructs;
specifically store the values in a List not an array.
Here are some hints:
List<Integer> valuesList = new ArrayList<Integer>();
for (int index = 0; index < 25; ++index)
Integer currentValue = Math.sqrt(index);
valuesList.add(currentValue);
for (int index = 25; index < 50; ++index)
Integer currentValue = index * 3;
valuesList.add(currentValue)
int count = 1;
for (Integer current : valuesList)
if ((count % 5) == 0) // write a newline.
System.out.print(current);
++count
Here is my method that is suppose to reverse the array.
(Also, keep in mind that this method can receive a jagged array)
public static int[][] reverse(int[][]a){
int[][] rev = new int[a.length][];
int row = a.length;
for(int x=0;x<a.length;x++){
int col = a[x].length-1;
for(int y=0; y< a[x].length;y++){
rev[row-1][col-1]= a[x][y];
col--;
}
row--;
}
return rev;
}// reverse method
I keep getting
Exception in thread "main" java.lang.NullPointerException
at Home.reverse(Home.java:259)
at Home.main(Home.java:56)
Java Result: 1
Here is my main that calls that method
int[][] two = {{1,2,3,4},{0,1,2},{9},{1,3,5,7}};
System.out.println("The size of array os " + ar.length);
System.out.println("The columns of array is " + ar[0].length);
int[][] rev;
//int[] b = concatenate(ar);
//int[] c = concatenate(two);
//int[][] rev = reverse(ar);
//for(int x=0;x<c.length;x++){System.out.println("worked" + c[x]);}
rev = reverse(two);
//for(int x = 0;x<rev.length;x++){
// for(int y = 0;y<rev[x].length;y++){
// System.out.print(rev[x][y]);
//}
//}
for(int x=0;x<rev.length;x++){
for(int y=0;y<rev[x].length;y++){
System.out.print(rev[x][y]);
}
}
}// main
So my question is really, where did I go wrong?
I traced my reverse method and it looks like it should be doing its job but apparently not.
Your array rev has not been initialized in its second coordinate. After your declaration int[][] rev = new int[a.length][], all your rev[i] are null objects (arrays are objects, even for primitive types). To avoid that, initialize with int[][] rev = new int[a.length][a[0].length] or with rev[i] = new int[a[i].length] or so, if the array is jagged.
When you say this line
int[][] rev = new int[a.length][];
You have created an array of length a.length of arrays, but the internal arrays are all null. So you are getting a NullPointerException on this line:
rev[row-1][col-1]= a[x][y];
You need to create your internal arrays inside the first for loop. This will satisfy your "jagged array" requirement.
for(int x=0;x<a.length;x++){
int col = a[x].length-1;
rev[row-1] = new int[a[x].length]; // Add this to create differing lengths.
for(int y=0; y< a[x].length;y++){