Java - Variable Scope

后端 未结 8 1501
心在旅途
心在旅途 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

    Your variable item has scope to the do while loop it is defined in.

    int exit = 0;
    String item = null; // <-- Add this
    

    then change your loop

    do {
        System.out.println("Enter item number: ");
        item = input.next(); // <-- Defined outside this scope now.
        if (ValidateItem(item) == true) {
            if (Integer.parseInt(item) <= 4 && Integer.parseInt(item) >= 1) {
                exit = 1;
            } else {
                System.out.println("Enter an item number between 1 and 4");
            }
        } else { // <-- just use else
            // if (ValidateItem(item) == false) {
            System.out.println("Enter an item number between 1 and 4");
        }
    } while (exit == 0);
    
    0 讨论(0)
  • 2020-12-22 09:38

    The item variable is declared in the first do while loop Hence you can access it inside the do while loop To access the item in the scope of the function, you should declare it before the do while loop, so that it can be accessed in the if(item==1) statement

    0 讨论(0)
提交回复
热议问题