错误:变量可能尚未初始化&如果声明

时间:2013-06-27 21:49:07

标签: java class variables initialization project

基本上,

 //Black ops 2 Class generator Please help me FIX!!!!!!
    import java.util.Scanner;
    import java.util.Random;
    public class money
        {
        public static void main(String[]args)
            {
        String primaryOption;
        Scanner scan = new Scanner (System.in);
        Random primaryGen = new Random();

        String weaponType; //Rifle, SMG, HMG, Sniper, shotgun, or special
        String primaryoption; //Do you want a primary?
        String primaryWeapon; //The gun you get
        int primaryWeapon1; 
        String primrayCamo; //Camo for primary
        String MTAR = "MTAR", Type25 = "Type 25", SWAT556 = "SWAT-556", FALOSW = "FAL-OSW", M27 = "M27", SCARH = "SCAR-H", SMR = "SMR", M8A1 = "M8A1", AN94 = "AN-94";

        String secondaryOption; //Do you want a secondary?
        String secondaryWeapon; //Your gun
        int secondaryWeapon1;
        String secondaryCamo; //Camo for secondary
        System.out.println("Would you like a Primary Weapon? Yes(1) or No(2)");
        primaryOption = scan.nextLine();
            if (primaryOption.equals("Yes")) {
                System.out.println("Would you like a Rifle, SMG, HMG, Sniper, Shotgun, or Special?)");
                weaponType = scan.nextLine();
                    if (weaponType.equals("Rifle")) {
                        primaryWeapon1 = primaryGen.nextInt(1) +1;
                        if (primaryWeapon1 == 1) {
                            primaryWeapon = MTAR; //*&%&*This is where i initialized it.
    }
                return; 

                            }
    System.out.println("Primary Weapon: " + primaryWeapon); //This is where the error is. It say's im not initializing the variable but I initialize it in the last if statement
    }
    }
    }

4 个答案:

答案 0 :(得分:1)

  

它说我不是在初始化变量,而是在初始化它   最后的if语句

如果没有执行“if”块,会发生什么?然后该变量将被取消分配吗?这就是编译器抱怨的原因。

应在所有可能的流中分配局部变量,否则它是编译时错误。

答案 1 :(得分:1)

您必须在使用变量之前对其进行初始化。如果if语句失败,则此变量将保持未初始化状态:

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

因此,在您声明它的地方,将其等同于""

String primaryWeapon = ""; //The gun you get

答案 2 :(得分:0)

在某些情况下PrimaryWeapon永远不会被初始化(只要PrimaryWeapon1不等于1)。

使用此功能并修复:

String primaryWeapon = "";

答案 3 :(得分:0)

我认为你的问题在于if语句: 假设你到达这里并且weaponType等于“步枪”,它将返回并退出你的功能。您应该将primaryWeapon初始化为默认值,即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
 }

同样完成if块,if(yes) {...} else {...}. java编译器将分支出条件子句,并在尝试使用未初始化的变量时发出警告/错误。例如:

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);

- 尼汝