通过我创建的下面的程序,它不允许我运行它,因为它声称该类是公开的并且应该被声明。如何修复它以便我可以成功运行程序?感谢。
这是我的完整代码:
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;
}
}
}
答案 0 :(得分:0)
您将两个类声明为同一个文件。
错误消息说,顶级公共类应该在他们自己的文件中声明,与该类具有相同的名称,就像评论中提到的@RoddyoftheFrozenPeas一样。
因此,您必须创建第二个文件,名为Dog.java
,并在评论中提及@ cricket_007,并在其中移动Dog
类。