java - 我的初学者代码有什么问题?
问题描述
我无法理解我的代码有什么问题。在这段代码中,当我尝试为类中的变量赋值时,我遇到了这样的错误。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{
}
解决方案
您在一行上声明了一个实例成员:
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)
推荐阅读
- javascript - “display:none”元素的宽度或高度为零是标准吗?
- javascript - 使用向下箭头键滚动 div 不起作用
- c - 试图理解一个递归函数来反转一个字符串
- r - 在 Rstudio 中按 source 只显示工作目录而不是运行代码
- ios - 获得正确重用标识符的问题
- java - 如何在两行上获取 JTable 标题文本
- react-native - Flutter apk/ipa 大小 vs React Native apk/ipa 大小
- flutter - 为什么背景过滤器会模糊我的整个应用程序
- android - 无法使用 Firebase 向 Microsoft 进行身份验证
- javascript - 数组长度不变