Java - Variable Scope

后端 未结 8 1502
心在旅途
心在旅途 2020-12-22 08:42

I\'m brand new to java and I have a super n00bish question. (I do have some general programming knowledge). I\'m trying to access the variable \"item\" to no avail. Can some

8条回答
  •  礼貌的吻别
    2020-12-22 09:33

    Variable scope only extends to the smallest pair of braces that surround the declaration. For instance:

    //this could be a method body, an if statement, a loop, whatever
    {
        int x;
    } //x passes out of scope here
    

    Therefore, when you declare item inside of a do-while loop, its scope ends once you exit the loop. To fix this, declare item above the loop like this:

    String item = null; //initialize to null to avoid warning about using an un-initialized variable
    
    do {
        System.out.println("Enter item number: ");
        item = input.next();
    
        //rest of loop...
    
    } while (exit == 0);
    

    This way item will be available until the method returns.

提交回复
热议问题