首页 > 解决方案 > 我的初学者代码有什么问题?

问题描述

我无法理解我的代码有什么问题。在这段代码中,当我尝试为类中的变量赋值时,我遇到了这样的错误。System.out.println 在此类中也不起作用: 1.Identifier 预期 2.Unexpected 令牌 3.Unknown 类“windows”

public static void main(String[] args) {

}

class building{
    int apart_num;
    apart_num = 3;
}

class apartments{
    double area;
    int lightbulb;
    int windows;
    windows = 4;
}

interface construct_building{

}

interface construct_apartments{

}

标签: javaclass

解决方案


您在一行上声明了一个实例成员:

int apart_num;

然后为其赋值:

apart_num = 3;

问题是这是在方法之外完成的,这些语句不能分开,你不能分配一个以前在块语句之外声明的变量。

在一行中完成(声明和分配):

class building{
    int apart_num = 3;
}

或使用构造函数

class building{
    int apart_num;

    public building(){
        apart_num = 3;
    }
}

或在块语句中

int windows;
{ //a block statement
    windows = 4;
}

然后,如果这段代码不是一个类,你需要这样做。

public MyClass{
    public static void main(String[] args){ ... }
    ...

    class Building { //inner class (will exist only inside of a MyClass instance

    }

    static class Apartment { // a nested class, exist whitout a MyClass instance

    }
}

class Level { //A class that have nothing to do  with MyClass and that can not be public.

}

其中 MyClass 是文件名 (MyClass.java)


推荐阅读