Java 字符串对象返回
我想确保这段代码返回的是字符串对象Java 字符串对象返回,java,Java,我想确保这段代码返回的是字符串对象 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", "
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.
}
没有理由返回
String.format(randomstation)
。只需返回随机语句
String.format(randomSequence)
确实返回字符串,但它将等于randomSequence
,因为您没有向format
方法传递任何其他参数。问题是什么?如果它没有返回字符串,它将返回什么?无论如何,内部的{}
是多余的,可以在不更改程序的情况下删除。当您将一个方法声明为返回类型为String
时,这意味着它可以返回对String
对象的引用,也可以返回null
,或者,它可以抛出异常
或错误
,也可以无法终止。没有其他选择。在您的例子中,是的,这将返回一个字符串。