0
我想做一個瘋狂的庫遊戲,用戶將輸入5個變量(名詞,形容詞,動詞,副詞,第二名詞),然後將在我的子類中使用不同的「庫」。問題是,當我輸入我的參數時,它將輸出爲空。我確信有一個簡單的方法可以爲不同的toStrings使用相同的輸入,但是我對新的繼承並不確定它的工作原理。子類toString打印null? (使用相同的參數爲不同的toStrings)
(我看了看其他的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());
}
}