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

后端 未结 8 1005
半阙折子戏
半阙折子戏 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:48

    The analysis Eclipse performs to determine whether the variable is assigned on every code path isn't intelligent enough to realize that the tests on numberOfWords will never all fail. Typically, because it's not possible to statically evaluate every possible condition, a compiler/syntax checker won't attempt to evaluate any of them. If you replaced the last "else if" with an "else" it should work, as at least one assignment to textCost will occur regardless of the conditions being tested.

    0 讨论(0)
  • 2020-11-27 23:48

    Even though you know one of the 3 branches of the comparison with numberOfWords will be visited, the compiler doesn't know that. It will wrongly assume that it is possible to enter the else clause and the textCost variable will remain unitiliazed.

    Similarly with the switch (advPay). Even though you know that one of the two will be visited, the compiler doesn't.

    Suggestion: Remove the else if (numberOfWords > 35) make it just an else.

    As for the switch (advPay), add a default case. Inside you can put a throw new AssertionError();.

    0 讨论(0)
提交回复
热议问题