0

I am trying to make a DeleteRecord() that takes any number of String[][] type arguments. I have made a sort of test function just to see what kind of logice iwould need to apply to make that function. I made it work but I want to use a foreach loop. how can I do that. I have this code:

public void testSomething(String[][]... enteredStrings) {
        for (int i = 0; i < enteredStrings[0].length; i++) {
            for (int j = 0; j < enteredStrings[0][i].length; j++) {
                System.out.println("i -> " + i + " " + "j -> " + j + " " + enteredStrings[0][i][j]);
            }
        }
    }

I know how to make foreach loop in java but I can't do it with a multidimensional array. Thanks in advance.

2
  • it's three dimensional my friend Commented Jun 5, 2011 at 18:13
  • If you intend on modifying the elements (since I see that you want to make a DeleteRecord()), your innermost loop should not be a foreach loop, otherwise the arrays won't be modified. Commented Jun 5, 2011 at 18:16

2 Answers 2

4

You need to loop through the String[]s in the outer array of strings-arrays:

for (String[] arr : enteredStrings) {
    for (String str : arr) {
        ...
    }
}
Sign up to request clarification or add additional context in comments.

9 Comments

The biggest hitch with a for-each loop given the provided code will be the third println. You are using the indices there, so if you need to maintain that line the way it is, you'll have to start with this and continue to track where you are.
@SLaks i think you are forgetting the part where testSomething() is a variadic type
I think Thomas is right here. Any time you need to keep track of the indices, you might as well just use a standard for loop.
I think enteredStrings is actually a 3d array.
yes it is. Eclipse shows a tooltip like this String[][][] enteredStrings. and my code body also shows that.
|
0

For a 3D array with your setup the code below will print the contents of the array. However, I'm not sure how you get the indices with a for each.

public void test2(String[][]... enteredStrings){
    for (String[] iii : enteredStrings[0]){
        for (String jjj: iii){
            System.out.println(jjj);
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.