在我创建的下面的程序中,它不允许我运行它,因为它声称该类是公共的,应声明。如何修复它,以便成功运行程序?谢谢。
这是我的完整代码:
class Dog {
String name;
int size;
// This is where the object is created in which the different dogs are given an attribute which in this case is a name which is a variable type string.
public void bark() {
if (size > 60) {
System.out.println(name+"says ruff!");
} else {
System.out.println(name +" says yip!");
}
}
public void play() {
System.out.println("woooooohoooooooooo mans playing games");
}
}
// This public class is the second class in which the method is tested and its where the different dogs are named and new dogs arrive.
public class DogTestDrive {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.name = "Bart";
dog1.size = 100;
Dog[] myDogs = new Dog[2]; // here is where the array of the dogs begins and it has already set the position to 2
myDogs[0] = new Dog();
// my dogs is a new class
myDogs[1] = dog1;
myDogs[0].name = "Fred";
myDogs[0].size = 43;
// This is where an array with the different dogs names were stored - these can count as attributes.
int x = 0;
while (x < myDogs.length) {
myDogs[x].bark();
myDogs[x].play();
x = x + 1;
}
}
}
您声明了两个类i同一文件。
错误消息说,最高公共类应在自己的文件中声明,其名称与类相同的名称,就像评论中提到的@roddyofthefrozenpeas一样。
因此,您必须创建一个名为 Dog.java
的文件,如 @cricket_007,并在其中移动Dog
类。