Initializing multidimensional arrays with enhanced for loop in java - java

I'm just playing around with my code, and was wondering if initializing a multidimensional array with the enhanced for loop is possible.
How do I fix this?
double[][] array2 = new double[2][5];
int b=1;
counter=0;
for(double[] x:array2)
{
for(double a:x)
{
array2[][counter]=b; //<- errors here
counter++;
b+=2;
}
}
//output what it contains
for(double[] x:array2)
{
for(double a:x)
{
System.out.println(a);
}
}
How would you guys do it with 3 dimensions?
double[][][] array3 = new double[4][5][6];
I know I could use Collections for this stuff but I was just trying things out.

Since you need an index to write into an array, you can’t use the enhanced for loop for updates. However, you are modifying only the innermost arrays in the case of a multi-dimensional array in Java. Therefore you can use the enhanced for loop for the outer arrays:
double[][] array2 = new double[2][5];
int b=1;
for(double[] x:array2) {
for(int index = 0; index < x.length; index++) {
x[index]=b;
b+=2;
}
}
The same applies to any number of dimensions:
double[][][] array3 = new double[4][5][6];
int b=1;
for(double[][] outer: array3)
for(double[] inner: outer)
for(int index = 0; index < inner.length; index++) {
inner[index]=b;
b+=2;
}

What you are trying to do makes no sense, since you must know the indices of the array in order to assign values to it.
The enhanced for loop hides those indices from you, so you'll have to maintain your own indices, which makes using the enhanced for loop pointless.
Sure, you can do something like this :
int b=1;
int row=0;
for(double[] x:array2)
{
int col=0;
for(double a:x)
{
array2[row][col]=b;
col++;
b+=2;
}
row++;
}
But since you are not using x and a, you can just use a regular for loop :
int b=1;
for(int row=0;row<array2.length;row++)
{
for(int col=0;col<array2[row].length;col++)
{
array2[row][col]=b;
b+=2;
}
}
You tell me which version is more readable.

Related

Write a function called arraySum that returns the sum (as an int) of all the values in a two-dimensional array of int values (Java)

I am trying to sum all the int values of a 2D array. I named it array. my function is then called arraySum. If arraySum is null, I return 0. Otherwise, it goes through two for-loops, summing the values of these arrays.
int i = 0;
int j = 0;
static int sum = 0;
int[][] array = new int[i][j];
static int arraySum(int[][] array) {
if (array == null) { // test if the incoming param is null
return 0;
} else {
for (int i = 0; i < array.length; i++) { // length of the outer array
for (int j = 0; j < array[i].length; j++) { // length of the inner array
sum += array[i][j];
}
}
return sum; // moved out of the loop
}
}
my error message:
java.lang.AssertionError: Incorrect result: expected [-217085] but found [-308126]
Fixing the method signature is the first step.
Then you'll need to fix the null check.
Then your loops need to check the size of the inner and outer arrays.
Move the return statement.
Here's the fixed code:
static int arraySum(int[][] array) { // fix the signature
if (array == null) { // test if the incoming param is null
return 0;
} else {
int sum = 0; // you need this in the scope of the method - it will be returned at the end
for (int i = 0; i < array.length; i++) { // length of the outer array
for (int j = 0; j < array[i].length; j++) { // length of the inner array
sum += array[i][j];
}
}
return sum; // moved out of the loop
}
}
Edit: I've concentrated on just the method now - how you call it is up to you. Please note that the method will not affect any externally defined sum variable. It will return the sum and it's up to the caller to store that value somewhere.
Avoid using primitive for statement. See following:
static int arraySum(int[][] array) {
int sum = 0;
if (array == null) return 0;
for(int[] row: array){
for(int col : row) {
sum += col;
}
}
return sum;
}
Streams can do this too:
//Create 2D array
int[][] array = {{1,2,3},{4,5},{6}};
//Sum all elements of array
int sum = Stream.of(array).flatMapToInt(IntStream::of).sum();
System.out.println(sum);
Picking apart the summing code:
Stream.of(array)
Turns the 2D array of type int[][] into a Stream<int[]>. From here, we need to go one level deeper to process each child array in the 2D array as the stream only streams the first dimension.
So at this point we'll have a stream that contains:
an int[] array containing {1,2,3}
an int[] array containing {4,5}
an int[] array containing {6}
.flatMapToInt(IntStream::of)
So far we have a Stream of int[], still two-dimensional. Flat map flattens the structure into a single stream of ints.
flatMapToInt() expands each int[] element of the stream into one or more int values. IntStream.of() takes an array int[] and turns it into an int stream. Combining these two gives a single stream of int values.
After the flattening, we'll have an int stream of:
{1,2,3,4,5,6}
.sum()
Now we have an IntStream with all elements expanded out from the original 2D array, this simply gets the sum of all the values.
Now the disclaimer - if you are new to Java and learning about arrays, this might be a little too advanced. I'd recommend learning about nesting for-loops and iterating over arrays. But it's also useful to know when an API can do a lot of the work for you.

How do I display the sum of the elements of myArray using nested enhanced for loops?

I have created a program for an assignment that requires me to display the elements of an array using nested enhanced for loops.
I get the error that it cannot convert from element type Integer[] to int.
myArray was already instantiated and initialized correctly in a constructor. I know that it's correct because I can display the elements of the array in list format just fine, from 1 to 60.
public void displayArrayProduct() {
DecimalFormat decimalFormat = new DecimalFormat("#.##");
decimalFormat.setGroupingUsed(true);
decimalFormat.setGroupingSize(3);
int p=1;
System.out.print("The product of all element of myArray is ");
for (int a : myArray) {
for (int b : myArray) {
p = p + myArray[a][b];
}
}
System.out.println(decimalFormat.format(p));
}
}
What I expected this to do was output the sum of all of the elements of the array. I tried the exact same thing with regular for loops, and it worked perfectly. Unfortunately when I swapped to enhanced for loops, it stopped working, giving me the error:
Type mismatch: cannot convert from element type Integer[] to int
This is what my constructor looks like:
ExerciseTwo() {
myArray = new Integer[6][10];
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray[i].length; j++) {
this.myArray[i][j] = i + 1;
}
}
}
for (int[] a : myArray) {
for (int b : a) {
p = p + b;
}
}
Well the issue is a is an int array and not just an int.
You're using for-each loops which go through each element in an array or collection. So the thing you define in the loop declaration is an element from the array, rather than an index. Since you're using a 2-dimensional array (an array of arrays), each element in myArray is an integer array, so the first loop should be declared:
for (int[] a : myArray) {
So each a value will be of type int[], and what you want next is to get each integer from each of those integer arrays:
for (int b : a) {
Note that you're getting each integer in a, not in myArray. Now you can reference each integer in the array as just b, not an array's value at index b:
p = p + b;
It looks like myArray is an array of arrays, not an array of ints. Maybe this is more what you need?
for (int[] a: myArray) {
for (int b: a) {
p = p + b;
}
}
Update: My original answer was posted before it was clear myArray is a multidimensional array. Given that, I agree with Vecna - who also correctly pointed out that using the for-each loop would allow you to get the integer itself instead of referencing it by index.
Original answer:
It looks like you may have changed something else when you converted the for loops.
The expression myArray[a][b] would be valid if myArray were a multi-dimensional array. The problem is that you are attempting to access a two-dimensional array, when the array itself is one-dimensional.
If you are attempting to multiply the entries at a and b, you'd need to do this:
p = p + myArray[a] * myArray[b];
or in shorthand:
p += myArray[a] * myArray[b];
You mentioned that you had 60 elements in your Array, so I simply created a sample 2 x 30 Array as an example:
int[][] myArray = new int[2][30];
int increment = 0;
for(int x = 0; x < myArray.length; x++) {
for(int y = 0; y < myArray[x].length; y++) {
myArray[x][y] = increment;
increment++;
}
}
Next, if you are using a for-each loop, your error is occurring because each individual row of the Array as an INDEX IN IT OF ITSELF. So your for-each loop should represent be of the type (int[]) an int Array:
for(int[] x: myArray) {
Within each individual Array (x) there is an int primitive value so we run another for-each-loop in order to extract each individual value:
for(int y: x) {
And here is your complete code:
for(int[] x: myArray) {
for(int y: x) {
totalVal += y;
}
}
System.out.println(totalVal);
And the output is the sum of each int in the Array:
1770

exception when trying to print an array in Java

I have this very little program in Java (just started to learn this language):
package hellojava;
public class Hellojava {
public static void main(String[] args) {
System.out.println("Hello World");
int[] nums = {1,2,3,4,5,6,7,8,9,10};
int[] revs = reverse(nums);
for (int i : revs) {
System.out.println(revs[i]);
}
}
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i=0, j=result.length-1; i<list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
}
It throws this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at hellojava.Hellojava.main(Hellojava.java:9).
So I pretty know what's wrong and know how to fix it, but my question is about that for loop. I thought that this enhanced for loop will work here, but it doesn't. Why's that?
The problem is that the enhanced for loop gives the values of the array, not the indexes. So, 10 the value is returned, which is an invalid index.
Your loop beginning:
for (int i : revs) {
is equivalent to
for (int index = 0; index < revs.length; index++)
{
int i = revs[index];
}
The enhanced for loop gives you the values in an array, not the indexes. Try
for (int i : revs) {
System.out.println(i);
}
Simple:
for (int i : revs) {
System.out.println(i);
}
You are using a foreach statement instead of a for indexed loop. The foreach loop iterates the array for you and assign the element of the array to i so don't consider it as an index of an array.
Here is an Oracle documentation on the For-Each Loop.
Replace
System.out.println(revs[i]);
with
System.out.println(i);
Explanation: The variable i is the integer element and not an index.

Java put matrix element in array

i was trying to compare 2 variables in java but it gives me error and i cant figure it out.
I am reading matrix element then put it in temp then put that temp variable in an array. but it gives error when I try to put matrix element in temp and when I compare elements.
error: array required, but float found. Anyone knows how to correct this ?
public float[] toSortedArray()
{
float b[];
float temp;
int index=0;
for(int i=1; i<=m; i++)
{
for(int j=1; j<=n; j++)
{
temp=a[m][n];
b[index++]=temp;
}
}
Arrays.sort(b);
System.out.print("[");
for(int z=0; z<(m*n)-1; z++)
{
System.out.print(b[z]+", ");
}
System.out.print(b[(m*n)-1]+"]\n");
}
There are several things needed in this:
Pass on the m, n parameter along with original 2D array like
public float[] toSortedArray(float[][] a, int m, int n)
define b array as
float b[] = new float[m*n];
In for loop (one within i and j var) (both loop should start with 0) use
temp=a[i][j];
instead of
temp=a[m][n];
At the end return b.
return b;

Array Index out of Bound exception in a program for reverse of an array

Here is the code to reverse an array
import java.util.*;
class middle {
public static void main(String args[]){
int a[]=new int[]{2,3,65,4,7,8,9};
int c[]=new int[a.length-1];
int k=0;
for(int i=a.length;i>0;i++){
c[k]=a[i];
k++;
}
System.out.println("Reverse of an array");
for(int i=0;i<c.length;i++)
System.out.print(c[i]+" ");
}
}
while running gives Array index out of bound exception:7
where the code is going wrong?
a.length is out of bound for a
for(int i=a.length;i>0;i++)
{
c[k]=a[i];
k++;
}
then,
int c[]=new int[a.length-1];
you need same length array for, not length - 1 for reverse array
To loop through the array backwards, you need to change all three conditions in your loop, like so:
for(int i=a.length-1;i>=0;i--)
{
c[k]=a[i];
k++;
}
Let's take this apart:
int i=a.length-1;
You must begin at a.length-1, as arrays use 0-based indexing and a.length is out of bounds.
i>=0;
You need to iterate until i>=0, as i>0 will miss one element of your array.
i--
You need to decrement i, as the loop will always access out of bounds indexes/never terminate otherwise.
P.S. As #Jigar mentioned, you need to initialize c as int c[]=new int[a.length];.
you did mistake here , you need to mention the length of array a.length not a.length-1 for c and the values in for loop conditions should have like for(int i=a.length-1;i>=0;i--) i should be decremented. : modified code is here:
int a[]=new int[]{2,3,65,4,7,8,9};
int c[]=new int[a.length];
int k=0;
for(int i=a.length-1;i>=0;i--)
{
c[k]=a[i];
k++;
}

Categories

Resources