java - 错误: variable might not have been initialized & if statement

标签 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
    }
    }
    }

最佳答案

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

如果不执行“if” block 会发生什么?那么该变量将被取消分配,对吧?这就是编译器提示的原因。

局部变量应该在所有可能的流程中赋值,否则会出现编译时错误。

关于java - 错误: variable might not have been initialized & if statement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58367879/

相关文章:

PHP:通过链接传递变量

c++ - 按类型命名变量是一种不好的做法吗?

java - 鱼类模拟游戏错误

java - 在 Java 中将 SHGetFileInfo 与 JNA 结合使用

java - 将数据添加到 JavaFX 表格 View 中

python - 迭代一个类型而不实例化它

variables - 直到某个特定的子串

java - 如何制作具有通用类型和 Android Fragment 继承的接口(interface)?

java - 从单独的类更新 JProgressBar

javascript - 如何使用 jQuery 将一组类的内容分发到另一组