loop array in oop code example
Example 1: arrays with for loops
// Another way to write search that combines
// the "end of array" and "found" logic in one
// while loop. As a matter of style, we prefer
// the above version that uses the standard
// for-all loop.
public int searchNotAsGood(int[] nums, int target) {
int i = 0;
while (i<nums.length && nums[i]!=target) {
i++;
}
// get here either because we found it, or hit end of array
if (i==nums.length) {
return -1;
}
else {
return i;
}
}
Example 2: arrays with for loops
Account[] accounts;
// 1. allocate the array (initially all the pointers are null)
accounts = new Account[100];
// 2. allocate 100 Account objects, and store their pointers in the array
for (int i=0; i<accounts.length; i++) {
accounts[i] = new Account();
}
// 3. call a method on one of the accounts in the array
account[0].deposit(100);