开发者

How use a global variable in if statement

I have this if statement and what to access axeMinDmg. How do i set it as a global variable to so that i can access it within the if statement. Also, how to i set minDmg as a global variable so that i can access outside of the if statement. thanks

   // if yes ask what weapon to purchase
   if (name.equals("ye开发者_JS百科s")){
       System.out.println("Select Your Weapon \n axe \n bat \n sword : \n  ");

       Scanner wc = new Scanner(System.in);
       String weapon = wc.next();


    if(weapon.equals("axe")){
    minDmg = axeMinDmg;   
   } else {
       System.out.println();
} // close if statement    


Global variables really does not exists in Java. You can create a public static final member of a class and the member will accesible in the same scope as the class (if public everywhere)

public class MyClass {

  public static final int axeMinDmg = 20;

can be used as MyClass.axeMinDmg from everywhere.

Another way could be to go with an Enum.


You can declare and initialize it outside the

 if (condition) {
 }

block. This will allow you to use it within if.

e.g.

 String minDmg = null; 
 String axeMinDmg = null;
 if (name.equals("yes")) { 
     ... 
 }

Hope I am answering your question as intended.


You can initialize it in the beginning of your class, so the if statement would be included in its scope.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜