Global Vairables in Java?

We are having issues with a function used to control our elevator in teleOp.

Basically, we need something like a global variable to use in teleOp. This is because when teleOp runs, the robot checks for the state of three buttons on a joystick (preset heights for the elevator): if one of them is being pressed, it sets a variable (targetPosition) to a value, and then sends it to the elevator function. Here’s the problem: if none of them are being pressed, it still needs to send the value to the function so that we can still move the elevator manually. But because a value was never assigned to the variable, it wants to be initialized with the value of 0 - one that is already used by the robot.

We need to be able to still use the elevator function without sending a variable, but Eclipse wants the variable to be initialized. Can we get around this by using a global variable so we don’t have to set it to 0? And if so, how would we go about doing this? (You’ll have to excuse my ignorance, what I tried didn’t work and this is my first year as programmer :p)

Any and all help is greatly appreciated!

You declare a variable as public static which will allow it to be used throughout your code without the need for an object, just reference the variable directly through the class name. FWIW, this is generally bad design. Out of curiosity, are you building an iterative or a command robot (or something else)?

You don’t need a static variable. Declare a variable in your class and then initialize it in robotInit. The variable is accessible by any method that is in the class.

If you feel that neither of these answers accomplish what you are looking for, post your code so people can get a better understanding of your problem.

What my team does is we have a Java class dedicated to all variables called Constants. We declare and give values to all our variables with the modifiers: public static final datatype, that way they are accessible by every class you could need them in and they’re all organized together in one place. You can therefore make a default value for your position in here and change it as you need.