How to avoid 'the local variable may not have been initialized'?

后端 未结 8 1149
半阙折子戏
半阙折子戏 2020-11-27 23:00
/*This is a program that calculates Internet advertising rates based on what features/options you choose.
 * 
 *  
 */

import java.util.Scanner;

public class Inter         


        
8条回答
  •  被撕碎了的回忆
    2020-11-27 23:41

    A good way to avoid such issues is to set the to be assigned variable as final and uninitialized before the checks. This will force you to set a value before you can use/read it.

    final textCostTmp;
    if (condition1) {
      textCostTmp = ...;
    } else if (condition2) {
      textCostTmp = ...;
    } 
    // if you use textCostTmp here the compiler will complain that it is uninitialized !
    textCost = textCostTmp;
    

    To solve this DO NOT initialize the variable as you may miss the missing else case. The only proper solution is to add an else case to cover all possible cases ! I consider it bad practice to initialize non final variables except for some rare scenarios like a counter in a loop.

    The proposed approach will force you to handle all possible cases, now and in the future (easier to maintain). The compiler is a bit stupid at times (cannot figure that numberOfWords > 35 is the else)...but the compiler is your ally not your enemy...

提交回复
热议问题