-2
我想確保這段代碼返回一個字符串對象。字符串對象返回
class ShoutBox extends Clone{
public static String ShoutOutRandomMessage(){
//holds the words to be generated.
String[] subject= {" Jim is", " Henry is", " Carter is"};
String[] verb= {" eating", " catching", " studying", " caughing"};
String[] adjective= {" funny", " hard", " good", " polite"};
String[] object= {" course", " homework", " books", " dog"};
String[] adverb= {" quickly. ", " everywhere. ", " accordingly. ", " awfully. "};
Random r = new Random(); //intialize a Random
int selectedElement = r.nextInt(subject.length);
{
//This Method will grab a word from the above list.
String randomSentence = subject[selectedElement]
+ verb[selectedElement]
+ adjective[selectedElement]
+ object[selectedElement]
+ adverb[selectedElement];
System.out.println("Here is your Random Generated Sentence"+"\n");
System.out.println(randomSentence + "\n\n");
//This method will print the random sentence.
return String.format(randomSentence);
}
//Is this code returning a string object.
}
問題是什麼? – sstan
如果它沒有返回* a *字符串,它返回什麼?無論如何,內部的'{}'是多餘的,可以在不改變程序的情況下移除。 – user2864740
當你聲明一個返回類型爲String的方法時,這意味着它可以返回一個String對象的引用,或者它可以返回null,或者它可以拋出一個Exception或者一個'錯誤「,否則它可能無法終止。沒有其他選擇。在你的情況下,是的,這會返回一個'String'。 –