【问题标题】:logical error in this java code, how do i resolve this error?这个java代码中的逻辑错误,我该如何解决这个错误?
【发布时间】:2013-12-15 16:00:57
【问题描述】:
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(希望这是有道理的)。 我是 Java 的初学者,我似乎无法完全理解如何使用书籍在 Java(或任何编程语言)中编码。我需要有人帮助才能完全理解编码。另请说明此代码是如何解决的,以便我了解问题以及将来如何解决这些类型的问题(希望如此)。

提前致谢。

【问题讨论】:

  • 它似乎几乎可以工作,但唯一的问题是“这只狗有 4 条腿”似乎没有执行。代码是 'System.out.println("this dog has"+ dog1.GetLeg()+"legs");");'

标签: java


【解决方案1】:

您不能只是将对象放在输出字符串中并期望它知道您的意思。

当您将常规对象添加到字符串时,它会调用其 toString() 方法,您尚未定义该方法并默认为看起来像一堆抓斗的东西...

相反,您需要执行System.out.println("this dog has"+ dog1.getLegs() +"legs"); 之类的操作,其他操作也一样。

【讨论】:

    【解决方案2】:

    您似乎没有调用方法,只是将对象插入字符串 - 大多数情况下这不会以合理的方式工作。尝试调用您已实现的“get”方法。

    "this dog has " + dog1.GetLegs() + " legs";
    "does this dog have a tail? " + dog2.GetTail();
    "this dog has " + dog3.GetFur() + " fur";
    

    【讨论】:

    • 它可以工作,但如何在显示的文本中添加空格?
    • 空格进入字符串文字:“Dogs”与“Dogs”,第二个将有一个尾随空格。所以你可以写成 "this" + " " + "dog" + " " + "has" + " " + dog1.GetLegs() + " " + "legs"
    【解决方案3】:

    在打印信息的行上,您打印对象而不是对象的属性之一。将第一个 System.out.println 更改为:

    System.out.println("this dog has"+ dog1.GetLeg() +"legs");
    

    我想你会弄清楚如何更改其他行:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-19
      • 2016-07-21
      • 2016-09-09
      • 1970-01-01
      • 2013-09-29
      相关资源
      最近更新 更多