0

I have a class assignment in which I must create a function that tests 4 integers for a combination lock. For example, let's call the parameters a, b, c, and d. In the function :

a can be 3, 5, or 7

b must be 2

c can be anywhere between 5 and 100, including 5 & 100

and d can be less than 9 or more than 20, but neither 9 not 20 will work

The function must test all of these numbers as "correct" for the combination to be correct. I've used switch statements to get the numbers to return properly, but is there a way I can test for all 4 numbers at once and for the code to stop when it reaches an incorrect number?

I tried something like the code below, but it returned as undefined. Probably because it is long and nonsensical.

    checkLock = function(a,b,c,d) {
     if (a === 3 || 5 || 7 && b === 2 && c >= 5 || c <= 100 && d < 6 || d > 
       20) {
         return "correct";
        } else {
          return "incorrect";
        }
    };

I've tried using some switch statements and alternating if..else statements. But it doesn't catch incorrect combinations.

I've looked at these resources on W3 Schools about switch statements, this article about nesting if...else statements, and articles from Front Stuff and other stack overflow questions to try and figure it out. I'm at a brick wall now.

1 Answers1

1

Since this is for a class assignment, I won't give you the code. Instead I will give you a hint.

Your if statement is invalid.

a === 3 || 5 || 7

You need a left hand assignment for the 5 and 7:

a === 3 || a === 5 || a === 7

You could also return early by first checking a. Something like:

if (a !== 3 && a !== 5 && a !== 7) {
  return 'incorrect'
}

This way would make the code neater, and the code after that would be simpler since you now know that a is correct.

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81