-4

I was trying the following code out.

    int index, use, comp;
    for (index = 0; index < 3; index++)
    {
        if (user1.equalsIgnoreCase(options[index]))
        {
            use = index;
        }
    }
    for (index = 0; index < 3; index++)
    {
        if (opt.equalsIgnoreCase(options[index]))
        {
            comp = add + index;
        }
    }
    int sum = comp + use;

At the line int sum = comp + use;, I am getting an error saying that variables comp and use are not initialized. How can I store the values I had gotten during the execution of the loop in these variables?

JensG
  • 13,148
  • 4
  • 45
  • 55

2 Answers2

1

The compiler is telling you that it is possible that comp and use will not have been given values by the time you reach the line int sum = comp + use;. This is clearly true (from the compiler's point of view): There is no way to be certain that these variables will have had values placed in them.

A simple way to solve this is to initialize them at the start:

int comp = 0;
int use = 0;

But be sure first that this will not mess up the functionality you want.

Eli
  • 693
  • 5
  • 12
0

You need to calculate the sum inside the for loop, otherwise, the two variables will be accessible (outside of the loop).

 int index;
 int sum = 0;
 int comp= 0;
 int use = 0; 
 //would've been better if you specified what these variables are for though.

    for (index = 0; index < 3; index++)
    {          
        if (user1.equalsIgnoreCase(options[index]))
        {
            use = index;
        }
        if (opt.equalsIgnoreCase(options[index]))
        {
            comp = add + index;
        }           
        sum = comp + use;
    }
Tebogo Khanye
  • 380
  • 1
  • 7
  • 18