0

所以基本上,

 //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

4 回答 4

1

它说我没有初始化变量,但我在最后一个 if 语句中初始化它

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

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

于 2013-06-27T21:50:48.127 回答
1

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

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

所以,在你声明它的地方,它等于""

String primaryWeapon = ""; //The gun you get
于 2013-06-27T21:50:59.503 回答
0

在某些情况下,PrimaryWeapon从未初始化(只要PrimaryWeapon1不等于1)。

使用它并且它是固定的:

String primaryWeapon = "";
于 2013-06-27T21:51:11.820 回答
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);

——尼鲁

于 2013-06-27T22:11:19.517 回答