2017-02-28 106 views
0

该程序编译正确,但不会运行时,当我尝试输入宽度和高度的值,而不是给我的错误消息“线程中的异常”主要“java .lang.IllegalArgumentException:宽度和高度必须为正值“。如何正确地声明我在主方法之外使用Scanner定义的静态变量? (初学编程的,对不起,如果这是显而易见的)非法参数异常 - 如何声明方法中定义的静态变量

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(); 
+0

请告知使用精确的线,你得到这个错误。也请打印宽度/高度值。 – john16384

+0

你的意思是'x0 = console.nextDouble();'而不是'double x0 = console.nextDouble();'? (对于其他3个变量也是如此)如果你打算分配静态变量或定义一个新的,无关的局部变量? –

+0

是的!这解决了我的问题,非常感谢。你介意解释为什么我以前的版本给我一个错误? – kellabd

回答

1

您声明这些字段:

static int width; 
static int height; 
static double x0; 
static double y0; 

但声明具有相同的名称,这些局部变量:

int width = console.nextInt(); 
int height = console.nextInt(); 
System.out.println("Please provide a starting position: "); 
double x0 = console.nextDouble(); 
double y0 = console.nextDouble(); 

所以你请勿将值分配给方法中的字段,而是分配给局部变量。
这些是两个不同的变量和局部变量阴影字段变量,它们具有相同的名称,因为它们在方法中具有优先级范围。

除了局部变量仅在getInputs()执行期间存在。

您应该删除的局部变量:

​​3210