有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java非法参数异常如何声明方法中定义的静态变量

这个程序编译正确,但当我试图输入宽度和高度的值时,它不会运行,而是给我错误消息“线程中的异常”main“java.lang.IllegalArgumentException:宽度和高度必须为正”。如何正确声明在main方法之外使用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();

共 (1) 个答案

  1. # 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()执行期间存在

    您应该删除局部变量:

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