Great success?

After a bit of work, I was able to get a solution that seemed at least somewhat elegant. The first version that passed was considerably worse with lots of repeated code.

When currentScreen == Screen.Pass the following function is called.

Feedback welcome!

Edit: Saw the rest of the lesson. What do you folks think? B+ effort?

void PasswordInput(string input) {
    int passCheck=0;

    if (level == 1) {
        if (input == "cafe") {
            passCheck = 1;
        }            
    }
    else if (level == 2) {
        if (input == "hospital") {
            passCheck = 1;
        }
    }
    else if (level == 3) {
        if (input == "space") {
            passCheck = 1;
        }            
    }

    if (passCheck == 1) {
        Terminal.WriteLine("Password Accepted");
    }
    else {
        Terminal.WriteLine("Wrong Password: Try again or [reboot]");
    }
}

image

1 Like

@Rob / @Nina would be awesome if you could give @Pretzel some feedback on the above?

Thanks,
Lucy

1 Like

Hi Pretzel,

I’m sorry that we missed your thread. Next time, please feel free to share your solution also in the Q&A section on Udemy to increase your visibility. :slight_smile:

Now on to your solution. In my opinion, it’s readable, it makes sense and it’s simple. That’s what I expect from a good solution.

Did you know that you could put two comparisons into the braces? For example:

if (level == 1 && input == "cafe") {
    passCheck = 1;
 }

This way you could avoid the nested ifs, which are not needed in this case. It’s not a mistake, though, just a suggestion.

Good job, and keep it up!

1 Like
  1. if else spaghetti level=1,2,3 could be rewritten as switch statement

  2. or because passCheck is always 1 in return statement there could be hashmap/dictionary with 1=cafe, 2=hospital, 3=space and it could be something like this pseudocode:
    a) return String.Equals(map[level], input) == true
    b) Terminal.WriteLine(String.Equals(map[level], input) ? “Password Accepted”) : “Wrong Password: Try again or [reboot]”);

  3. if (input == “cafe”)…I come from Java and String is also object (string in C# is just shortcut for System.String). Therefore you should write comparison as:

a) “cafe”.Equals(input)
b) String.Equals(input, “cafe”)

Privacy & Terms