error: variable might not have been initialized & if statement

后端 未结 4 474
一生所求
一生所求 2020-12-04 01:32

So basically, the

 //Black ops 2 Class generator Please help me FIX!!!!!!
    import java.util.Scanner;
    import java.util.Random;
    public class money
         


        
相关标签:
4条回答
  • 2020-12-04 01:45

    There are cases where PrimaryWeapon is never initialized (whenever PrimaryWeapon1 is not equal to 1).

    Use this and it's fixed:

    String primaryWeapon = "";
    
    0 讨论(0)
  • 2020-12-04 01:55

    I think your problem lies in this if statement: Assuming you get here and weaponType does equal "rifle", it will return and exit your function. You should initialize your primaryWeapon to a default value, i.e. primaryWeapon = "None";

     if (weaponType.equals("Rifle")) {
                            primaryWeapon1 = primaryGen.nextInt(1) +1;
                            if (primaryWeapon1 == 1) {
                                primaryWeapon = MTAR; //*&%&*This is where i initialized it.
                            }
                            return; //<---- remove this
     }
    

    Also complete the if block, if(yes) {...} else {...}.The java compiler will branch out conditional clauses, and will warn/error when attempting to use unintialized variables. For example:

    int b;
    boolean f = true;
    if(f)
        b =1;
    System.out.println(b); //error because no else block
    
    
    //Fixed
    int b; 
    boolean f = true;
    if(f)
    b = 1;
    else
    b= 2;
    System.out.println(b);
    

    --Niru

    0 讨论(0)
  • 2020-12-04 01:59

    You have to initialize the variable before you use it. If if statement fails, this variable will stay uninitialized:

     System.out.println("Primary Weapon: " + primaryWeapon); 
    

    So, where you declare it, equal it to "":

    String primaryWeapon = ""; //The gun you get
    
    0 讨论(0)
  • 2020-12-04 02:05

    It say's im not initializing the variable but I initialize it in the last if statement

    What happens if that "if" block is not executed? Then that variable will be un-assigned right? That is why compiler complaining.

    Local variable should be assigned in all possible flows, otherwise it is compiletime error.

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