2016-03-16 75 views
1

我需要使用在if語句內創建的變量。我的代碼,但是,不編譯。我只需要幫助編譯它,同時保持功能相同。Java - 使用在if語句中創建的變量

下面是代碼的片段

else if (in.equals("Monster") && in1.equals("Orc")) 
    { Players Character = new Orc(); 
    System.out.println("You have chosen "+in+" type "+in1+". Monsters in general are more attack orientated"); 
    } 
    Character.addAttack(5); 
+7

你只需要在if之外聲明'Character'。 – user2004685

回答

3

爲了使它在您的if條件之外工作,您只需在之外聲明條件。

/* Declare it here */ 
Players Character = null; 

if(...) { 
/* Do Something Here */ 
} else if (in.equals("Monster") && in1.equals("Orc")) { 
    Character = new Orc(); 
    System.out.println("You have chosen " + in + " type " + 
         in1 + ". Monsters in general are more attack orientated"); 
} 

/* Now you can use it here */ 
Character.addAttack(5); 
2

你必須移動if外面聲明:

Players character = null; 
// ... 
else if (in.equals("Monster") && in1.equals("Orc")) 
{ 
    character = new Orc(); 
    System.out.println("You have chosen "+in+" type "+in1+". Monsters in general are more attack orientated"); 
} 
// TODO: check for null 
character.addAttack(5); 

一些閱讀有關變量的範圍:http://www.cs.berkeley.edu/~jrs/4/lec/08

+1

您可能還想鏈接到[命名約定](http://www.oracle.com/technetwork/java/codeconventions-135099.html)(因爲您已經修復了他的變量名稱)。 – Tom

+0

謝謝你的工作,編譯並運行 – duldi

+1

感謝您的鏈接@Tom –