【问题标题】:How to get my program to print out?如何让我的程序打印出来?
【发布时间】:2016-02-09 05:18:35
【问题描述】:

在尝试让我的程序为我的 AP 计算机科学课程工作时遇到问题。已在代码中进行了注释以显示我的问题。谢谢大家。

Java 类

import java.util.*;
public class Allosaur extends Dinosaur
{
private boolean hungry;
private String response, answer;
private String Allosaur;

 // Prompt asks for 3 constructors: A Default constructor, a constructor with just a name, and a constructor with a name and hunger "response"

public Allosaur()
{
}

public Allosaur(String name)
{
 Allosaur=name;   
}

public Allosaur(String name, boolean hungry)
{
    Allosaur=name;
    this.hungry=hungry;
}

// Used this method to "find out" whether the dinosaur is hungry or not
public boolean getHunger()

{
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Are you hungry? ");
    response = keyboard.next();
    if(response.equals("Yes"))
    hungry = true;
    else if(!response.equals("Yes"))
    hungry= false;

    return hungry;

}

// Asks us to print out "RRRRRRR" if the dinosaur is NOT hungry and "HUNGRRRRRRRY" if the dinosaur IS hungry   

public String roar()
{
    if(hungry == true)
    answer = "HUNGRRRRRRRY";
    else if(hungry == false)
    answer = "RRRRRRR";

    return answer;
}

//When I use the toString() method in my driver class, none of these pop up, why?

public String toString()
{
    String Dino = super.toString();
    Dino = "The Dinosaur's name is: " + Allosaur;
    Dino += "Is the Dinosaur hungry? :" + getHunger() + "\n" + roar();
    return Dino;

} 

}

这是我的驱动程序类:

public class DinosaurMain extends Allosaur
{
public static void main(String[] args) 
{
       Allosaur Dino = new Allosaur("Jacob");
       Dino.toString();

}

}

我很困惑为什么我运行程序时什么都没有显示。

【问题讨论】:

  • 打印语句在哪里。您正在创建一个对象,然后在其上调用 toString()
  • 声明一个与其类同名的字段?这是一个新的低点......

标签: java string object tostring


【解决方案1】:

请求字符串输入后没有任何显示,因为您只是在 DinosaurMain 中以Dino.toString() 进行调用。这只是为您的对象制作字符串表示。它不会打印出该字符串表示形式。如果您将其更改为System.out.println(Dino.toString());,您会看到结果。

【讨论】:

  • 其实应该还是打印了一些东西,因为toString()方法调用了getHunger(),它打印了一些东西。
  • 是的,它打印出 getHunger() 方法,但在我的问题之后它就停止了。
  • @Sweetcharge 好的,这是有道理的。当你说什么都没出现时,我开始担心了。
猜你喜欢
  • 2021-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-06
  • 2021-02-02
  • 1970-01-01
相关资源
最近更新 更多