1

Let's say I got this array:

String[][]array = new String[5][5];

array[2][2] = desperate;

Would it be possible to find whether

String s = "desperate"; - equals any array element without using a for loop, and without having to manually enter the row column combination of the array assigned the value "desperate"?

1
  • Out of curiosity: what do you need a two-dimensional array of strings for? Commented Sep 28, 2012 at 13:50

4 Answers 4

3

while loop instead of for loop

int i = 0;
int j = 0;  
while (i < n)  
{  
   while (j < m)  
   {  
      if (array[i][j].equals("..."))
      {  
         /// 
      }  
      j++;
   }   
   i++;    
}  
Sign up to request clarification or add additional context in comments.

1 Comment

I don't think the style of loop is really the key to the question, and generally most people prefer for loops stackoverflow.com/q/3875114/106261
2

Use enhanced-for loop: -

String [][] array = new String[2][2];
array[1][1] = "desperate";
array[0][1] = "despee";
array[1][0] = "despete";
array[0][0] = "dete";

for (String[] innerArr: array) {
    for (String value: innerArr) {
         if (value.equals("desperate")) {
             System.out.println(value + " == desperate");
         }
    }
}

Output: - desperate == desperate

A better way that I would suggest is to use ArrayList<String> to store your items.. Then you can just call contains() method to check whether the list contains that element..

List<String> listString = new ArrayList<String>(); 
listString.add("desperate");
listString.add("despe");

if (listString.contains("desperate")) {
     System.out.println("True");
}

Output: - True

2 Comments

In the enhanced for loop does (String[] innerArr: array) only search the row arrays?
Exactly.. Outer loop fetches you each row.. which is itself an array.. Now taking the variable(innerArr) from outer loop, we iterate over it to get each element..
1

Assuming that you can't (for any reasons) change your array to another collection type:

String[][]array = new String[5][5];
array[2][2] = "desperate"; 


public boolean contains(String str){
  return new HashSet<String>((List<String>)Arrays.asList(array)).contains(str);
}

Better than transforming it to a List since HashSet's contains() method is O(1) and the one from List is O(n).

Comments

0

The only way to avoid using a loop (and it not clear why you would want to) is to use a Map which you pre-build with all the strings and indexes.

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.