2015-07-04 119 views
-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. 

    } 
+2

问题是什么? – sstan

+0

如果它没有返回* a *字符串,它返回什么?无论如何,内部的'{}'是多余的,可以在不改变程序的情况下移除。 – user2864740

+0

当你声明一个返回类型为String的方法时,这意味着它可以返回一个String对象的引用,或者它可以返回null,或者它可以抛出一个Exception或者一个'错误“,否则它可能无法终止。没有其他选择。在你的情况下,是的,这会返回一个'String'。 –

回答

0

没有理由返回String.format(randomSentence)。只需返回randomSentenceString.format(randomSentence)会返回一个字符串,但它将等于randomSentence,因为您没有将任何附加参数传递给format方法。

相关问题