I'm preparing for the Java OCA exam but there are several tricky questions about how iterates a multidimensional array.
So, if I had this array and I wanted to iterate using the for and for-each loops what would all be ways to do it?
I usually used only these three:
int [][]matrix = {{3,4,5},{6,7,8},{9},{10,11,12}};
//First way
for (int [] a : matrix){
for (int i =0; i<a.length;i++){
//code
}
}
//Second way
for (int []a: matrix){
for (int i: a){
//code
}
}
//Third way
for (int i = 0; i<matrix.length; i++) {
for (int j=0; j<matrix[a].length; j++) {
//code
}
}
//Fourth way???
Thanks a lot!
You missed the for, foreach combination:
for (int i = 0; i<matrix.length; i++) {
for (int j: matrix[i]){
// code
}
}
You can also use while loops instead of for. Can you be more specific about the context, so we can help you properly with what you need?
Related
I have a problem with Arrays.
UPDATE:
I need to insert elements from Array A to Array B, staring with uneven indexes and even ones afterwards. for example: A[0] should become B[10], A1=B[0],A[2]=B[11] etc.
I have updated the code (Thank you all for comments, tips and suggestions!).
for (i=0; i<10; i++){
if (i%2==1)
B[C-1]=A[i];
C++;
}
for (i=0; i<10; i++){
if (i%2==0)
B[C]=A[i];
C++;
}
Now it does fill Array B, but only every other element. See picture: Right now output is like this
How do get the B array to fill in right?
Sorry, if this all sounds stupid, I just started to learn programming.
This is not the most elegant or efficient solution, but I think it's simple enough to understand and follow.
public static void main(String[] args) {
double[] a = {0,1,2,3,4,5,6,7,8,9};
double[] b = new double[a.length];
double[] tempArray = new double[a.length];
int tempCounter = 0;
int indexCounter = 0;
for(int i = 0; i<a.length; i++){
if (a[i] % 2 == 0){ // even
tempArray[tempCounter] = a[i];
tempCounter++;
}else{
b[indexCounter] = a[i];
indexCounter++;
}
}
for(int i = 0; i<tempCounter; i++){
b[indexCounter] = tempArray[i];
indexCounter++;
}
}
Thank you all, after all suggestions, I was able to get it right!
for (i=1; i<20; i++){
if (i%2==1){
B[C]=A[i];
C++;
}
}
for (i=0; i<19; i++){
if (i%2==0){
B[C]=A[i];
C++;
}
}
This is my first time asking a question here, so forgive me if my formatting is a little sloppy.
I need to know how to set all the elements of a 2D Array to the same value, using for loops, with Java.
I was able to get this far:
import java.util.Arrays;
public class TheArray{
public static void main (String[] args){
int[][] pixels = new int[768][1024];
for(int i = 0; i < pixels.length; i++){
for(int j = 0; j < pixels[i].length; j++){
Arrays.fill(pixels[i], 867);
}
}
}
}
However I have no idea if I have done it right. So all I want it to do is make all of the elements of the 2D array be 867.
You don't need to use Arrays.fill if you're already using for loops. Just do:
for(int i = 0; i < pixels.length; i++){
for(int j = 0; j < pixels[i].length; j++){
pixels[i][j] = 867;
}
}
Arrays.fill would be used instead of the inner for loop.
Use the following line inside your loop:
pixels[i][j] = 867;
I created an ArrayList of arrays, but I don't know how to print them.
Here's what I am trying to do:
int j=0;
for (int i=0; i<aArray.length-1; i++){
exp=new int[100];
if (Character.isDigit(aArray[i])){
if(Character.isDigit(aArray[i])==true && aArray[i-1]=='-'){
exp[j]=Character.getNumericValue(-(aArray[i]));
}
else{
exp[j]=Character.getNumericValue(aArray[i]);
}
System.out.print(exp[j]);
j++;
}
}
System.out.println(" ");
list.add(exp);
}
for (int i=0; i<5; i++){
System.out.println(list.get(i)[i]);
}
All I get is 5 zeros. What am I missing? Practically, I read a .txt file in my program, and all I want to do, is seperate and write the numbers of each in the exp[] arrays and then save them in list (ArrayList of Arrays).
Add a for loop to go through each array in the list too:
for (int i=0; i<5; i++){
int[] tmp = list.get(i);
for (int j=0; j<tmp.length; j++) {
System.out.println(tmp[j]);
}
}
edit: You also need to be adding the array to the arraylist inside the for loop, otherwise you're adding a null array.
for (int i=0; i<aArray.length-1; i++){
exp=new int[100];
if (Character.isDigit(aArray[i])){
if(Character.isDigit(aArray[i])==true && aArray[i-1]=='-'){
exp[j]=Character.getNumericValue(-(aArray[i]));
}
else{
exp[j]=Character.getNumericValue(aArray[i]);
}
System.out.print(exp[j]);
j++;
}
System.out.println(" ");
list.add(exp);
}
Problem solved guys, I just needed to initialize exp array outside "for" loop, place a "while" loop and that's all!
Thank you for your answers!
I want to print out the elements of this multidimensional array but I get the index out of range error.
public class test {
public static void main(String[] args) {
int array1[][]={{1,2,3,4},{5},{6,7}};
for (int i=0; i<3;i++){
for (int j=0; j<4;j++){
System.out.println(array1[i][j]);
}
}
}
}
The problem is that with the loop, written like this, you assume that the nested arrays are all of length of 4 (and they are not). You'd better do:
for (int i=0; i < array1.length;i++) {
for (int j=0; j < array1[i].length;j++) {
...
}
}
Yes, because the second "subarray" doesn't have 4 elements. It would be better to do this dynamically:
// Note preferred syntax for array types - keep all the type info in one place.
int[][] array1 = {{1,2,3,4},{5},{6,7}};
for (int i = 0; i < array1.length; i++) {
for (int j = 0; array1[i].length; j++) {
System.out.println(array1[i][j]);
}
}
This way the iteration count of the inner loop depends on the array being iterated over.
An alternative is to use the enhanced for loop:
for (int[] subarray : array1) {
for (int value : subarray) {
System.out.println(value);
}
}
2 points regarding the following solution (and the other similar answers):
for (int i=0; i < array1.length;i++) {
for (int j=0; j < array1[i].length;j++) {
...
}
}
Here it wont make much difference, as the code is very short, but for better performance you should always avoid repeated calculations if the result never changes. array1's length wont change so calculating its length every iteration is not efficient. This would be improved solution.
int array1Length = array1.length;
for (int i=0; i < array1Length;i++){
int array1InnerLength = array1[i].length;
for (int j=0; j < array1InnerLength;j++){
...
}
}
Some people may suggest using ++j / ++i instead of i++ and j++ for better performance, you can read more about it here: What is the difference between ++i and i++?. Its not that critical imo, but it improves understanding of the code you're writing.
I've got a program where the user is giving the program the size of the array ie(the column and row size) and I am trying to give every position in the array the same value. I'm having an issue with my loop though, here it is.
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
//CODE
}
}
I can see that the issue is I am trying to give a value to a position that doesn't exist but I have no idea how to work around this issue. Any help would be appreciated :)
Try working with length, not with user input:
// ask user for sizes
int col = ...;
int row = ...;
// declare the array, let it be of type int
// it's the last occurence of "row" and "col"
int[][] data = new int[row][col];
// loop the array
for (int r = 0; r < data.length; ++r) { // <- not "row"!
int[] line = data[r];
for (int c = 0; c < line.length; ++c) { // <- not "col"!
// do what you want with line[c], e.g.
// line[c] = 7; // <- sets all array's items to 7
}
}
working with actual array's dimensions just prevent you from accessing non-existing items
From the code snippet you provided it seems you are fine. Maybe the array is not well initialized or you mismatched the row and column numbers. Try to use more specific variable names than 'i' and 'j'.
in java
try{
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
//CODE
}
}
}catch(IndexOutOfBoundsException exp){
System.out.printlv(exp.getMessage());
}
To begin, what makes you say that you "can see that the issue is I am trying to give a value to a position that doesn't exist"? What symptoms are you seeing that makes you believe this?
On the face of it, your code looks fine, however (and this is a big however) you have omitted the most important bits of code, viz the declaration of your 2D array, and the part inside the loop body where you assign the value to the array member. If you add these then I, or somebody else, may be able to help further.
Solution:
int matriz[][] = new int [row][col];
for(int i = 0; i <row; i++){
for(int j = 0; j < col; j++){
matriz[i][j] = 0;
}
}
//try this one
import java.util.Scanner; //Scanner class required for user input.
class xyz
{
public static void main(String ar[])
{
int row,col;
Scanner in=new Scanner(System.in); //defining Object for scanner class
System.out.println("Enter row");
row=in.nextInt();
System.out.println("Enter Column");
col=in.nextInt();
int mat[][]=new int[row][col]; //giving matrix size
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
mat[i][j]=0; //or any value decided by you
}
}
}
}