The code below produces the compiler error Variable HEIGHT might not have been initialized
(same goes for WIDTH
).
How can I declare an uninitialized static final variable like what I'm trying to do below?
public static final int HEIGHT, WIDTH;
static{
try {
currentImage = new Image("res/images/asteroid_blue.png");
WIDTH = currentImage.getWidth();
HEIGHT = currentImage.getHeight();
}catch (SlickException e){
e.printStackTrace();
}
}
static {
Image currentImage = null;
try {
currentImage = new Image("res/images/asteroid_blue.png");
} catch (Exception e) {
// catch exception - do other stuff
} finally {
if (currentImage != null) {
WIDTH = currentImage.getWidth();
HEIGHT = currentImage.getHeight();
} else {
// initialise default values
WIDTH = 0;
HEIGHT = 0;
}
}
}
Whatever happens (try/catch), you have to assign values to the static variables - therefor, finally should be used.
The right way would be to set the values to null
(in case its an object), but since it's final
you'll have to do this roundabout:
public static final int HEIGHT, WIDTH;
static{
int w = 0, h = 0;
try {
currentImage = new Image("res/images/asteroid_blue.png");
w = currentImage.getWidth();
h = currentImage.getHeight();
}catch (SlickException e){
e.printStackTrace();
}
WIDTH = w;
HEIGHT = h;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With