# theory behind testing each element of an array.

Printable View

• February 4th, 2010, 04:35 PM
etidd
theory behind testing each element of an array.
Given an array of ints, return true if the array contains a 2 next to a 2 somewhere.

has22({1, 2, 2}) → true
has22({1, 2, 1, 2}) → false
has22({2, 1, 2}) → false

public boolean has22(int[] nums)
{ ...}

maybe i could say...

Code :

```for (int i = 0; i <= nums.length; i++) { int twoCounter = 0; if (nums[i].equals(2)) twoCounter++; if (nums[i + 1].equals(2)) return true; }```

help me out with the rest of this.
• February 5th, 2010, 02:38 AM
Shambolic
Re: theory behind testing each element of an array.
Do you read through your code systematically? Pretend you are a dumb computer, reading every line literally and doing what it says. For example, in the code you have written, what is the purpose of the variable twoCounter? You won't learn to program by getting people on a forum to write all your code for you!

Having said that, the way I would write the code as follows:

Code :

```boolean pairoftwos = false;   for (int i = 0; i < nums.length-1; i++) { if (nums[i].equals(2) && nums[i + 1].equals(2)) pairoftwos = true; }   return pairoftwos;```
• February 5th, 2010, 08:04 AM
etidd
Re: theory behind testing each element of an array.
i already figured it out. thanks though.