简体   繁体   中英

Changing a variable outside the scope of a method in Java

So I'm trying to change the value of a minimum and maximum guess (with the actual guess being made by a random number generator) in order to stop the program from guessing the same number twice.

I have a method that makes a guess but also tries to set a lowest and highest guess which then changes when the method is used again

public static int takestab (int low, int high) {  
    int estimate;
    estimate = (low + (int)(Math.random() * ((high - low) + low)));

    if (estimate < number) {
        lowestguess = estimate;
    }
    else if (estimate > number) {
        highestguess = estimate;
    }
    return estimate;
}

Also, these are the vars I have outside of the method scope:

    int lowestguess = 1;
    int highestguess = 100;

So by running that method, the guess could be 50 and the actual number could be 60. if that's the case, then "lowestguess" becomes 50 so that the function can't guess any lower than 50.

When I try it this way, the cmd prompt says that it cant find the matching symbol.

Any ideas?

The problem is that lowestguess is an instance variable but your trying to access through a static method.

Options

  • pass the lowestGuess as a non-primitive (Object) to the method.
  • use a non-static method
  • make lowestGuess be static

Passing lowestGuess

Example:

public static int takestab(int low, int high, Integer Lowest)

This allows you to also make changes to Lowest as it is by reference .

Non Static Method

Change method to public int takestab(int low, int high)

Change LowestGuess to static

You should be careful in multi-threaded environments with this option.


See:


Finally, if you were programming in an IDE such as eclipse you would have error highlighting in which errors such as this become obvious faster.

lowestguess is an instance variable, it cannot be accessed without creating an instance. If you want to use it inside the static method then either you create an instance of your class and then use lowestguess , or if it makes sense then turn lowestguess as static .

The reason why non-static members are not allowed to be used in a static way is that, the memory initialization of instance variables happen when the object is created. And a static method can be called without creating an instance of the class.

A static method can only use static members (and local var of course). Your members lowestguess & highestguess should therefore be declared as static .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM