子类到字符串打印空?(对不同的 toString 使用相同的参数)



我正在尝试制作一个疯狂的库游戏,用户将输入 5 个变量(名词、形容词、动词、副词、第二名词),然后在整个子类中用于不同的"库"。问题是当我输入参数时,它会将它们打印为 null。我确信有一种简单的方法可以将相同的输入用于不同的 toString,但我是继承的新手,不确定这部分是如何工作的。

(我查看了其他 toString 空问题,但它们都不太适合我的情况,或者它们的构造函数有问题。我相当确定我的没有错。

这是我的短语超类:

public class Phrase 
{
private String noun;
private String adjective;
private String verb;
private String adverb;
private String noun2;
public Phrase (String n, String a, String v, String ad, String n2)
{
n=noun;
a=adjective;
v=verb;
ad=adverb;
n2=noun2;
}
public String getNoun()
{return noun;}
public String getAdj ()
{return adjective;}
public String getVerb ()
{return verb;}
public String getAdverb ()
{return adverb;}
public String get2Noun ()
{return noun2;}
//i'll need the get methods in the libs classes and the set methods in the 
while loop, if user wants to change parameters
public void setNoun (String Newnoun)
{noun=Newnoun;}
public void setAdj (String newAdj)
{adjective=newAdj;}
public void setVerb (String newVrb)
{verb=newVrb;}
public void setAdverb (String newAdv)
{adverb=newAdv;}
public void set2Noun (String newNoun2)
{noun2=newNoun2;}
}

这是我的子类:

public class Obama extends Phrase
{
public Obama(String noun, String adjective, String verb, String adverb, 
String noun2)
{super (noun, adjective, verb, adverb, noun2);}
public String getNoun()
{return super.getNoun();}
public String getAdj ()
{return super.getAdj();}
public String getVerb ()
{return super.getVerb();}
public String getAdverb ()
{return super.getAdverb();}
public String get2Noun (String n)
{return super.get2Noun();}

public String toString()
{
return ("there is a " + super.getAdj() + " " + super.getNoun() +" on the 
floor! It is " + super.getVerb() +"ing " + super.getAdverb() +". Next to it 
is a " + super.get2Noun()); 
}

}

这是我的驱动程序:

public class Madlibsdriver 
{
static Scanner scan= new Scanner (System.in);
public static void main(String[] args) 
{
System.out.print ("Welcome to Mad libs!");
System.out.println();
System.out.println("-------------------------------------------- ");
System.out.println("Enter a noun:");
String ip1= scan.nextLine();
System.out.println("Enter an adjective:");
String ip2= scan.nextLine();
System.out.println ("Enter a verb:");
String ip3= scan.nextLine();
System.out.println ("Enter an adverb (ex: angrily) :");
String ip4= scan.nextLine();
System.out.println ("Enter another noun:");
String ip5= scan.nextLine();
Phrase obama= new Obama(ip1, ip2, ip3, ip4, ip5);
System.out.println();
System.out.print (obama.toString());
}
}

您已经交换了构造函数中的参数,设置了传入的值(而不是使用它们来设置本地字段)。使用this关键字捕获此类错误,例如

public Phrase (String n, String a, String v, String ad, String n2)
{
this.noun = n;
this.adjective = a;
this.verb = v;
this.adverb = ad;
this.noun2 = n2;
}

相关内容

  • 没有找到相关文章

最新更新