我正在学习Java,目前我正在学习一本书,这是本书提供的代码:
package Person;
public class Person {
private String lastName;
private String firstName;
private int age;
public Person(String last, String first, int a) { //constructor
lastName = last;
firstName = first;
age = a;
}
public void displayPerson() {
System.out.print(" Last name: " + lastName);
System.out.print(", First name: " + firstName);
System.out.println(", Age: " + age);
}
public String getLast(){
return lastName;
}
}
class ClassDataArray {
private Person[] a;
private int nElems;
public ClassDataArray(int max){
a = new Person[max];
nElems = 0;
}
public Person find(String searchName){
int j;
for(j = 0; j<nElems; j++){
if(a[j].getLast().equals(searchName)){
break;
}
}
if(j == nElems){
return null;
}else{
return a[j];
}
}
public void insert(String last, String first, int age){
a[nElems] = new Person(last, first, age);
nElems++;
}
public boolean delete(String searchName){
int j;
for(j = 0; j<nElems; j++){
if(a[j].getLast().equals(searchName)){
break;
}
}
if(j == nElems){
return false;
}else{
for(int k = j; k<nElems; k++){
a[k] = a[k + 1];
}
nElems--;
return true;
}
}
public void displayA(){
for(int j = 0; j<nElems; j++){
a[j].displayPerson();
}
}
//////////////////////////////////////////////////////
class ClassDataApp{
public static void main(String[] args){
int maxSize = 100;
ClassDataArray arr;
arr = new ClassDataArray(maxSize);
arr.insert("Evans","Parry", 24);
arr.insert("Smith","Lorraine",37);
arr.insert("Yee","Tom", 43);
arr.insert("Adams","Henry", 63);
arr.insert("Hashimoto","Sato",21);
arr.insert("Stimson","Henry",29);
arr.insert("Velasquez","Jose",72);
arr.insert("Lamarque","Henry",54);
arr.insert("Vang","Minh",22);
arr.insert("Creswell","Lucinda",18);
arr.displayA();
String searchKey = "Stimson";
Person found;
found = arr.find(searchKey);
if(found != null){
System.out.print("Found ");
found.displayPerson();
}else{
System.out.println("Can't find " + searchKey);
}
System.out.println("Deleting Smith, Yee, and Creswell");
arr.delete("Smith");
arr.delete("Yee");
arr.delete("Creswell");
arr.displayA();
}
}
}
但是我收到了错误:
The method main cannot be declared static; static methods can only be declared in a static or top level type
我认为创建一个单独的文件可以解决这个问题,但我正在关注一本书,所以我可能会错过一个概念?本书没有告诉我创建另一个.java
文件。它只是文件中的两个类,其中一个包含static main
。请有人提供某种见解,谢谢!
答案 0 :(得分:2)
除非是拼写错误,否则在}
之前错过了结束class ClassDataApp{
答案 1 :(得分:1)
您应该将您的课程放入不同的文件中。您将ClassDataApp嵌套在ClassDataArray
中答案 2 :(得分:1)
阅读本文:http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html 它有一个很好的例子。如果嵌套,ClassDataApp可以是静态的。
答案 3 :(得分:1)
public static main(String [] args)将被视为程序的入口点,只有当它放在公共类中时。 .java文件只能有一个公共类。
如果要将所有类保留在同一个java文件中,请仅将ClassDataApp类设为public。
否则,将它们放在不同java文件的同一个包中,并确保ClassDataApp是公共的,其他类至少不是私有的。