好的,所以我只是学习java,并使用这个:http://www.myflex.org/books/JavaKid8x11.pdf教程。我目前在第37页,我似乎无法骑过鱼。我很确定我完全复制了代码,但显然我做错了,所以这是我的代码。 这是班级宠物:
public class Pet {
int age;
float weight;
float height;
String color;
public void sleep() {
System.out.println(
"Good night, see you tommorow");
}
public void eat() {
System.out.println(
"I'm so hungry...let me have a snack like nachos!");
}
public String say(String aWord) {
String petResponse = "OK!! OK!! " +aWord;
return petResponse;
}
}
这是鱼类的超级类:
public class Fish extends Pet {
public String say(String something) {
return "Don't you know that fish do not talk?";
}
int currentDepth=0;
public void sleep() {
System.out.println("I need to rest");
}
public int dive(int howDeep) {
currentDepth=currentDepth + howDeep;
System.out.println("Diving for " + howDeep + " feet");
System.out.println("I'm at " + currentDepth + " feet below sea level");
return currentDepth;
}
}
FishMaster使用Fish类:
public class FishMaster {
public static void main(String[] args) {
Fish myLittleFish = new Fish();
myLittleFish.say("Hello!");
myLittleFish.dive(2);
myLittleFish.dive(3);
myLittleFish.sleep();
}
}
问题是当我试图在Fish类中过度使用say方法时。虽然过度骑行睡眠方法工作正常,但说方法不再做任何事情了。我跑了,它不打印“难道你不知道鱼不能说话吗?”正如这本书所说的那样。我做错了什么,或者说假设功能只是假设不打印任何东西。感谢您的反馈。谢谢。
答案 0 :(得分:3)
该方法返回一个String,它不会打印它。尝试:
System.out.println(myLittleFish.say("Hello!"));
澄清:
// we assign the string returned from the method to a variable
String sentence = myLittleFish.say("Hello!");
// we print the variable to screen
System.out.println(sentence);
答案 1 :(得分:1)
你的所有say()
方法都返回一个字符串。调用函数(FishMaster.main()
)对此String没有任何作用。我希望你能用以下内容打印出来:
System.out.println(myLittleFish.say("Hello!"));
答案 2 :(得分:0)
您忘了将其打印到系统中。该值仅在未打印时返回。