Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

java - variable access outside of if statement

I am trying to access variable outside an if statement in java. The variable is axeMinDmg. Here is what i have but getting an error. I want minDmg = axeMinDmg. thanks

    @SuppressWarnings("unused")
    public static void main(String[] args)
        throws IOException
        {


            int count = 1;

    // start both with 1 point  
    int goodTotal = 50;
    int monTotal = 50;

    // set amount of money that Goodman has
    int moneyAmt = 10;




    // setting array for bat

    int [] bat = {2, 4, 3};
    int batMinDmg = bat[0];
    int batMaxDmg = bat[1];
    int batCost = bat[2];

    //setting array for axe
    int [] axe = {4, 6, 6};
    int axeMinDmg = axe[0];
    int axeMaxDmg = axe[1];
    int axeCost = axe[2];

    //setting array for sword

    int [] sword = {6, 8, 10};
    int swordMinDmg = sword[0];
    int swordMaxDmg = sword[1];
    int swordCost = sword[2];



   // ask if Goodman would like to purchase a weapon   
   System.out.println("Would you live to purchase a weapon (YES OR NO): ");
   Scanner sc = new Scanner(System.in);
   String name = sc.next();


   if (name.equals("yes")){
       System.out.println("Select Your Weapon 
 axe 
 bat 
 sword : 
  ");

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

    if(weapon.equals("axe")){
     int minDmg = axeMinDmg;
   } else {
       System.out.println();
} // close if statement    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll need to define the variable outside of the if statement to be able to use it outside.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...