[英]<identifier> expected compilation error in Java[3]
import java.io.*;
class attendance_and_student_management {
BufferedReader bw = new BufferedReader(new InputStreamReader(System.in));
File f5 = new File("e.txt");
f5.createNewFile();
File f4 = new File("d.txt");
f4.createNewFile();
File f3 = new File("c.txt");
f3.createNewFile();
File f2 = new File("b.txt");
f2.createNewFile();
File f1 = new File("a.txt");
f1.createNewFile();
}
I am trying to create 5 files at the beginning of my program, however when I compile my program the compiler highlights f5.createNewFile ();
我正在尝试在程序的开头创建5个文件,但是当我编译程序时,编译器会突出显示
f5.createNewFile ();
and give the error expected. 并给出预期的错误。
You need to wrap your code in a method. 您需要将代码包装在一个方法中。 You can't have normal statements directly inside a class.
您不能在类内部直接使用普通语句。
A good method for you to wrap this in is in a main
method: 一个好方法可以将其包装在
main
方法中:
import java.io.*;
class attendance_and_student_management {
public static void main(String[] args) {
BufferedReader bw = new BufferedReader(new InputStreamReader(System.in));
File f5 = new File("e.txt");
f5.createNewFile();
File f4 = new File("d.txt");
f4.createNewFile();
File f3 = new File("c.txt");
f3.createNewFile();
File f2 = new File("b.txt");
f2.createNewFile();
File f1 = new File("a.txt");
f1.createNewFile();
}
}
By putting it in a main
method, you can directly invoke this class from the command line with java -cp <classpath> attendance_and_student_management
. 通过将其放在
main
方法中,可以使用java -cp <classpath> attendance_and_student_management
从命令行直接调用此类。
Note that by Java naming conventions, class names should use CamelCase and start with a capital. 请注意,根据Java命名约定,类名称应使用CamelCase并以大写字母开头。 So the proper name for your class per these conventions is
AttendanceAndStudentManagement
. 因此,根据这些约定,您的班级的专有名称是
AttendanceAndStudentManagement
。
You can have "normal statements" in a class as static initialization like this: 您可以在类中将“普通语句”作为静态初始化,如下所示:
public class AttendanceAndStudentManagement {
BufferedReader bw = new BufferedReader(new InputStreamReader(System.in));
static {
try {
File f5 = new File("e.txt");
f5.createNewFile();
File f4 = new File("d.txt");
f4.createNewFile();
File f3 = new File("c.txt");
f3.createNewFile();
File f2 = new File("b.txt");
f2.createNewFile();
File f1 = new File("a.txt");
f1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Depending on your use case, this may be preferable to adding a main() method because it also works in presence of a main() method in another class. 根据您的用例,这可能比添加main()方法更好,因为它也可以在另一个类中存在main()方法的情况下工作。 The static blocks are executed when the class is loaded, ie before the first object is instantiated or the first call to a static method.
在加载类时,即在实例化第一个对象之前或在第一次调用静态方法之前,将执行静态块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.