2013-06-27 182 views
0

所以基本上,錯誤:變量可能尚未初始化和if語句

//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 
    } 
    } 
    } 
+0

'字符串primaryWeapon = 「徒手」;' – jxh

回答

1

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

如果說「如果」不執行塊會發生什麼?那麼這個變量將被分配正確嗎?這就是編譯器抱怨的原因。

應該在所有可能的流程中分配局部變量,否則就是編譯時錯誤。

1

您必須在使用它之前初始化變量。如果if語句失敗,這個變量將保持未初始化:

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

所以,在這裏你聲明它,等於它""

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

在有些情況下PrimaryWeapon從未初始化的情況下(只要PrimaryWeapon1不等於1)。

使用此,它的固定:

String primaryWeapon = ""; 
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(yes) {...} else {...}. Java編譯器會另闢蹊徑條件子句,並嘗試使用unintialized變量時會發出警告/錯誤。例如:

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