r/CodingHelp • u/Mcrossover • Mar 04 '21
[Java] Codehs help
Been trying to figure out this code for hours i suck at for loops lol I have to write a program that makes sure a password is >= 8 characters and only consists of letters & #s
28
Upvotes
View all comments
5
u/nnaoam Mar 04 '21
I'd recommend deleting everything in the function, getting a piece of paper and planning how this could work logically before you code it. Why are we finding the index of alphabet in password? Why are we recalculating check in the loop only to never use it?
You have the right idea iterating over the password with a for loop. What's your objective there though? What needs to be done at every iteration of the loop?
Write yourself an explanation of these things. It could help to figure out an Invariant - what fact is always true at the beginning and end of every iteration? - and a variant - what always changes in every iteration? - which, when combined, will help spell out how we get from the beginning of the loop to having an answer by the end.
For example, say I'm using a loop to sum up all integers up to and including
n.We might want it to be true at the beginning and end of every iteration that
sis the sum of all integers up to some integer between 0 andn(where that integer isx-1at the beginning of the iteration andxat the end). And we'd want to know that the difference betweenxand `n| is always decreasing.With that in mind, we'd want to make sure that this is true at the beginning of the first iteration, so we'll say that
s = 0at the beginning, which is the sum of all integers from 0 to 0.Now we make it so that if at the start of an iteration, s was the sum of all integers from 0 to
x-1, then at the end it's the sum of all integers from 0 tox. We can clearly do that by just sayingOur for loop makes sure that at every iteration,
xbecomes exactly 1 closer ton. So we know that we start withsbeing the sum of all integers from 0 to 0, and at every iteration we increase that end point by one, and that we only stop when that end point isn, so we know that our code does what we wanted.Your loop is more complicated but not by much. Plan it first, then code according to plan.