C
C#3mo ago
rigamortus

code help

uhhh im trying to run a program that will count how many 1s are in a string of binary, and if its odd or even itll do something, but it just doesnt work?
No description
19 Replies
rigamortus
rigamortusOP3mo ago
just doesnt work
Jimmacle
Jimmacle3mo ago
it's doing exactly what you told it to
while (findInstance1 != -1)
{
findInstance1 = binary.IndexOf(one)
}
while (findInstance1 != -1)
{
findInstance1 = binary.IndexOf(one)
}
when will this loop end?
rigamortus
rigamortusOP3mo ago
oh.. it ends when all the ones have been found i guess but i have no clue how to add that now that i think about it
Jimmacle
Jimmacle3mo ago
nope it loops forever
rigamortus
rigamortusOP3mo ago
i mean i want it to do that but its not yk
Jimmacle
Jimmacle3mo ago
IndexOf finds the index of the first instance of that character in the string, it doesn't keep moving if you keep calling it
rigamortus
rigamortusOP3mo ago
i was trying to get it to count all the 1s in the loop and i guess i forgot that it doesnt remove them uhhh
Jimmacle
Jimmacle3mo ago
i think you're overengineering the code a bit, it can be simpler you can loop over characters in a string directly like
foreach (var character in "myString")
{
if (character == '1')
{
count++;
}
}
foreach (var character in "myString")
{
if (character == '1')
{
count++;
}
}
rigamortus
rigamortusOP3mo ago
oh visual studio like suggested that but idk what var means so i didnt wanna use it no point if i cant learn from it yk
Jimmacle
Jimmacle3mo ago
it's just a shortcut, it's exactly the same as if you typed char there
rigamortus
rigamortusOP3mo ago
alright ill try it
Jimmacle
Jimmacle3mo ago
it figures out what the type should be based on the context
rigamortus
rigamortusOP3mo ago
No description
rigamortus
rigamortusOP3mo ago
like this?
Jimmacle
Jimmacle3mo ago
yeah, but you don't need the while loop or the first bit that searches for the first 1 your foreach loop does all that you need to count the 1s in the string
rigamortus
rigamortusOP3mo ago
No description
rigamortus
rigamortusOP3mo ago
so this should work oh wait i need to rename one2 what
rigamortus
rigamortusOP3mo ago
No description
rigamortus
rigamortusOP3mo ago
uhh nvm fixed it t ty**
Want results from more Discord servers?
Add your server