Is this Loop and Method right?
Hey, i just did Brackeys C# beginner course and i just wanted to try out some things. I did a Wizard class and i wanna do a Method where the class can "train" to get spellslots and there is a risky or normal way, while he can only do this train when the spellslots var is over 0. Is this code here right? Or should i change something.
18 Replies
You compare the learn type in the loop but the value doesn't change in the loop so you read the value multiple times when it's not needed
You should check it once then do a different loop depending on the type
The core logic is also the same between both types so you could have a single loop but using variables instead of constants
The value of these variables being set when checking the type
Ahhh i see, thanks a lot!
Same thing for checking the number. It's generated outside the loop so you should check outside and run the loop differently based on if < or >
Consider that if < or > is true, the loop will only iterate once then exit
So really no need for loops
And if neither, it will loop forever because spellSlots doesn't change
Hmm but doesnt it break when one if statement is true? or did i understood the "break;" command wrong, coz i thought that will stop the while loop and go on
break stops the loop
continue skips to the next iteration
Ah okay i understand
If you meant to use continue, that also isn't needed because it doesn't skip any code that would run otherwise
No i thought that if i call the method it would ask me once what if statement i want to go and after that it would break the loop and go out of the method. I think i will have a look after i got my sleep 😄 im trying to get used to write clean & short code before i start something bigger ^^
Then that would be return
Just don't need a loop if it can only run once anyway
Oh okay, will write that down then and test it out tomorrow. Thanks 🙂 (Coding makes the brain tired :D)
you should pass the rng as a parameter, and also generate the numbers inside the loop
@Redoxi
What do you mean exactly as a parameter?
parameter to your method
if you don't know what that means, ask google
Ahhh you mean this right? :
public void SpellSlotsTrain(int spellSlots)
So basically a parameter acts as a variable inside a method i think?
yes
but not the spell slots
the rng
Ahh right, read that wrong. that means that the rng should be outside of the method? So So that i can use it anyhwere in the class right? Or did i understood that wrong.
It's a thing that should be reused
Wherever you need random numbers, or anything for that matter, prefer passing it in as opposed to creating a new one
it's called dependency inversion
Oh okay i see, that makes sense. Thanks a lot!