Reputation: 9
This program compiles correctly, but doesn't run when I attempt to input values for width and height, instead giving me the error message "Exception in thread "main" java.lang.IllegalArgumentException: width and height must be positive". How do I correctly declare static variables that I define using Scanner outside the main method? (beginner programmer, sorry if this is obvious!)
public class Animation {
static int width;
static int height;
static double x0;
static double y0;
public static void main ( String[] args ) {
getInputs();
initStdDraw(width, height);
drawFace(x0, y0);
}
public static void initStdDraw(int width, int height) {
StdDraw.setCanvasSize(width, height);
StdDraw.setXscale(0, width);
StdDraw.setYscale(0, height);
StdDraw.rectangle(width/2, height/2, width/2, height/2);
}
public static void getInputs() {
Scanner console = new Scanner(System.in);
System.out.println("Please provide a canvas width and height: ");
int width = console.nextInt();
int height = console.nextInt();
System.out.println("Please provide a starting position: ");
double x0 = console.nextDouble();
double y0 = console.nextDouble();
Upvotes: 0
Views: 222
Reputation: 131346
You declare these fields:
static int width;
static int height;
static double x0;
static double y0;
But you declare these local variables with the same name :
int width = console.nextInt();
int height = console.nextInt();
System.out.println("Please provide a starting position: ");
double x0 = console.nextDouble();
double y0 = console.nextDouble();
So you don't assign the value to the fields in your method but to local variables.
These are two distinct variables and local variables shadow field variables with the same name as they have a priority scope in a method.
Besides local variables exist only during the getInputs()
execution.
You should remove the local variables :
width = console.nextInt();
height = console.nextInt();
System.out.println("Please provide a starting position: ");
x0 = console.nextDouble();
y0 = console.nextDouble();
Upvotes: 1