Working on a progamming problem witn MyProgrammingLab involving Java arrays: - \
ID: 3815219 • Letter: W
Question
Working on a progamming problem witn MyProgrammingLab involving Java arrays:
- "k" is initialized as an integer
- "currentMembers" is declared and initialized as an integer array
- "memberID" is declared and initialized as an integer
- "isAMember" is declared as a boolean
The goal is to have isAMember set to true if memberID is found in currentMembers; set to false if it's not. Below is my answer.
for (k = 0; k < currentMembers.length; k++)
{
if (currentMembers[k] == memberID)
isAMember = true;
else
isAMember = false;
break;
}
Something in my code causes the value to remain as false even when a match is found, but I can't figure out what. Any help would be greatly appreciated.
Explanation / Answer
Your code will just check the first iteration and then stops iterating. This is because of the break statement you placed in the loop. In first iteration it will compare the first element with memberId and set the isAMember flag accordingly and after this it encounters break statement and comes out of the loop.
What I understand is that you want to place break statement if at any iteration, element in the array becomes equal to member id. It will work for your code. Here is the corrected code snippet: -
for (k = 0; k < currentMembers.length; k++)
{
if (currentMembers[k] == memberID) {
isAMember = true;
break;
}
else
isAMember = false;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.