The problem is this: I set a variable in the method, then I create an array in which, depending on the value of the counter, the formulas for calculating these variables change, after all if, the cycle should postpone the sum of the obtained values ​​and write to the array. but it gives an error. that the variables were not described (not calculated). Please tell me how to remove the error. I give the approximate code below. Ps is required if to replace with switch. But the error there also remains.

public static void Ar() { double A,B,C,At,q=50; if (q <30) { A = 0; } else { A=... // какая-то опред. формула. эт неважно } for (int i = 0; i < 2; ++i) { if (i == 0) { A = ... // какая-то опред. формула. эт неважно B = ... // какая-то опред. формула. эт неважно C = ... // какая-то опред. формула. эт неважно } if (i == 1) { A= ... // какая-то опред. формула. эт неважно B = ... // какая-то опред. формула. эт неважно C =... // какая-то опред. формула. эт неважно } Array[i] = A+B+C; } } 
  • so your Array not defined anywhere, what should it be according to your idea? - Grundy
  • I understand that we are talking about variables A, B, C In the place of their declaration, explicitly initialize them, for example, double A = 0, B = 0, C = 0; instead of double A, B, C; (so that the compiler was sure that these variables will be necessarily initialized by the time they are added here: Array[i] = A+B+C; ) - StateItPrimitive
  • @Grundy I know this, I did not mention in the description of the problem simply .. in this program, all the rules, everything is set everywhere, but the error is issued on summation. that such variables are not described anywhere, although the if value will be assigned a new value each time - user204299
  • @StateItPrimitive exactly. Thank! Everything is fine now - user204299

1 answer 1

The compiler rightly believes that the variables B and C may not be initialized, because they did not receive initial values ​​during the declaration, and you initialize them only if certain conditions are met if (i == 0) and if (i == 1) . In fact, of course, initialization should occur, since you have a cycle from 0 to 2, but the compiler is not smart enough to predict it in compile-time.

In your case, you must specify an initial value for B and C. Or, in each if set the formula Array[i] = A+B+C;

  • rather, it assumes that something can happen and the code will not go into these conditions - Grundy