public class DogOwner extends Dog {
public static void main(String[] args){
Dog dog1 = new Dog ();
Dog dog2 = new Dog();
Dog dog3 = new Dog();
dog1.setLegs(4);
dog1.setTail(true);
dog3.setFur(" furry fur");
System.out.println("this dog has"+ dog1.GetLeg()+"legs");
System.out.println("does this dog have a tail?"+ dog2.Gettail());
System.out.println("this dog has"+ dog3.GetFur());
} }
}
} enter code here
enter code here
public class Dog {
/** variables**/
int Legs;
boolean tail;
String Fur;
/** returns the Legs variable (getter) **/
public int GetLeg(){
return Legs;
}
/** stores method variable Llgs within variable legs (setter) **/
public void setLegs(int legs){
this.Legs=legs;
}
/** returns the tail variable (getter) **/
public boolean Gettail(){
return tail;
}
/** stores method variable tail within variable tail (setter) **/
public void setTail(boolean tail){
this.tail=tail;
}
/**because the void does not work with String data type, the type String
* replaces void to make this code work (Hovercraft Full Of Eels, 2013)
* Hovercraft Full Of Eels.2013.why is this code not working in Java?.
* accessed from:http://stackoverflow.com/questions/20588830/why-is-this-code-not-working-in-java.
* stockoverflow.com. [accessed: 14/12/2013]**/
public String GetFur(){
return Fur;
}
/**stores for the method variable within the parameter variable Fur **/
public void setFur(String fur){
this.Fur=fur;
}
}
我想要的输出是: 这条狗有4条腿,
这只狗有尾巴吗?诚然, 这只狗有毛茸茸的皮毛文本true不应该是文本,它应该执行布尔值,在这种情况下,它应该执行true而不使用quoatation标记(希望这是有道理的)。 我是Java的初学者,我似乎无法完全理解如何使用书籍在java(或任何编程语言)中进行编码。我需要某人的帮助才能完全理解编码。另外请解释这段代码是如何解决的,以便我能够理解问题以及如何在将来解决这些类型的问题(希望如此)。
提前感谢。
答案 0 :(得分:1)
您不能只将对象放在输出字符串中,并希望它知道您的意思。
当你将一个常规对象添加到一个字符串时,它调用它的toString()
方法,你没有定义它,默认为看起来像一堆grable ...
相反,您需要执行类似System.out.println("this dog has"+ dog1.getLegs() +"legs");
的操作,同样需要执行其他操作。
答案 1 :(得分:1)
您似乎没有调用方法,只是将对象插入到字符串中 - 这在大多数情况下都不会以合理的方式工作。尝试调用您已实现的“获取”方法。
"this dog has " + dog1.GetLegs() + " legs";
"does this dog have a tail? " + dog2.GetTail();
"this dog has " + dog3.GetFur() + " fur";
答案 2 :(得分:0)
在打印信息的行上,打印对象而不是其中一个属性。将第一个System.out.println更改为:
System.out.println("this dog has"+ dog1.GetLeg() +"legs");
我想你会弄清楚如何改变其他行:)