无法让我的程序适用于我的AP计算机科学课程。已在代码中发表评论以显示我的问题。谢谢你们/ gals。
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();
}
}
我很困惑为什么在我运行程序时什么都不会出现。
答案 0 :(得分:3)
请求String输入后没有显示任何内容,因为您只是在DinosaurMain中以Dino.toString()
进行调用。这只是为您的对象创建String表示。它没有打印出String表示。如果您要将其更改为System.out.println(Dino.toString());
,您会看到结果。