Reputation: 13
So I'm pretty new to Java, and I'm trying to write a for loop to go through all of the pixels in an image, but for some unknown reason, the for loop never increments. When I try to run the code, it prints out the height and the width of the image, that are assigned to the variables "height" and "width" respectively, and then enters the for loops but only prints out 0, and 0 before finishing running.
public class ImageProcessor {
public static Pic image;
public static Pic modImage;
public static int width;
public static int height;
public static int average;
public static Pixel modPixel;
public static void main(String[] args) {
Pic image = new Pic(args[0]);
int width = image.getWidth();
int height = image.getHeight();
System.out.println(width);
System.out.println(height);
greyscale();
}
public static Pic greyscale() {
for (int w = 0; w <= width; w++) {
for (int h = 0 ; h <= height; h++) {
System.out.println(w);
System.out.println(h);
}
}
return image;
}
}
Upvotes: 0
Views: 168
Reputation: 111389
Your main method declares width
and height
as local
variables, shadowing the static variables with the same names and leaving them set to their default value of 0
. Change the code in the main method to:
width = image.getWidth();
height = image.getHeight();
Upvotes: 6
Reputation: 22646
The problem is you are not assigning the getWidth and getHeight result to the static variables at the top.
Because you've written:
int width = ...
it has actually created a new local variable called "width". When the greyscale method is called it has no knowledge of this variable.
If you changed those lines to be:
width = ...
It'll assign it to the static variables.
As a general principle, what would be even better is to avoid passing state around using global (i.e. static) variables at all. Instead give the greyscale method everything it needs when you call it.
public static Pic greyscale(int width, int height)
This means you never have to rely on the outside state of the world being correct when you are in the method, makes reasoning about your program easier and makes it less likely that you'll introduce bugs by altering width/height unexpectedly from other bits of code.
Upvotes: 1
Reputation: 201537
Your main method defines local variables of the same name; they shadow your static width
and height
fields;
public static int width; // <-- default to 0.
public static int height; // <-- default to 0.
public static void main(String[] args) {
Pic image = new Pic(args[0]);
width = image.getWidth(); // <-- use the static width
height = image.getHeight(); // <-- use the static height
System.out.println(width);
System.out.println(height);
greyscale();
}
Upvotes: 0