Jump to content

Code help C#

l3igwill
Go to solution Solved by fizzlesticks,

If "noTimes > mostOccurences" is never true or letter.length is 0, you never set a value for position. To use a variable it must be initialized on every possible path your code may take.

I cannot seem to figure out why the value J isn't stored into the position. In the display line it says that Letter[position] is a unassigned local variable.

This is just one method of a program.

private void CheckCharacter(string userInput) {

         char[] Letter = userInput.ToArray();
         int mostOccurences=0;
         int noTimes = 0;
         int position;

         for (int i = 0; i < Letter.Length; i++) {
            for (int j = 0; j < Letter.Length; j++) {
               if (Letter[j] == Letter[i]) {
                  noTimes++;
               }
               if (noTimes > mostOccurences) {
                  mostOccurences = noTimes;
                  position = j;
               }
            }
         }
         characterLabel.Text = "The " + Letter[position] + " occured the most at " + mostOccurences + " Times.";
           
      }

 

Link to comment
Share on other sites

Link to post
Share on other sites

If "noTimes > mostOccurences" is never true or letter.length is 0, you never set a value for position. To use a variable it must be initialized on every possible path your code may take.

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

shouldn't you be like resetting the "noTimes" after each loop

and I would suggest you swap the for-j-loop to be like

for(int j=i, noTimes=0; j<Letter.Length; j++)


 

that way you will reduce the number of necessary iterations in half and your "noTimes" will correctly count only the current letter it's checking instead of all letters

when the "mostOccurences" stays at zero you can just output the first letter as all of them occurred just once

 

as to why your position doesn't get save, I'm not entirely sure if you give it a non empty string it should be fine

CPU: Intel i7 5820K @ 4.20 GHz | MotherboardMSI X99S SLI PLUS | RAM: Corsair LPX 16GB DDR4 @ 2666MHz | GPU: Sapphire R9 Fury (x2 CrossFire)
Storage: Samsung 950Pro 512GB // OCZ Vector150 240GB // Seagate 1TB | PSU: Seasonic 1050 Snow Silent | Case: NZXT H440 | Cooling: Nepton 240M
FireStrike // Extreme // Ultra // 8K // 16K

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×