如何在另一个方法中包含返回的字符串 - java

时间:2014-03-23 08:48:48

标签: java string methods return

这可能是一个非常基本的问题,但由于我只是一个初学者,这让我感到困惑。我正在尝试将字符串的第一个字母大写,我用以下代码完成:

public String capitalizeFirstLetter(String product){ 
    String productCap = product.substring(0, 1).toUpperCase() + product.substring(1); 
    return productCap; }

然后,这个大写版本的产品只能放在一个字母编写方法中:

public void writeALetterChallenge(String nameFirst, String nameLast, String city, String    product, String company, double retail, int numItem){ 
UI.println("Dear " + nameFirst); 
UI.println(" You have been especially selected from the people of " + city); 
UI.println("to receive a special offer for "+ product); 
UI.println(productCap + " from " + company + " is a premium brand prodcut and");             UI.printf("retails for $%1.2f" + ". But, " + nameFirst + ",if you order your " + product + "\n", (retail)); 
UI.println("today, you can purchase it for just $" + (retail - (retail * 0.60)) + ", a saving of 60%!"); 
UI.println("As a special bonus, just for the " + nameLast + "family, if you order");     UI.println(numItem + " " + product + " today, you will get an additional 10% off - ");     UI.println("an amazing price for " + product + " of just $" + (retail - (retail * 0.70)) + "!"); 
UI.println(" "); 
UI.println("Hurry today and send in your order for " + product + " from " + company);     UI.println("and make these fantastic savings."); 
UI.println(" "); }

但是我的问题是,当我编译时,我得到了无法找到productCap的错误。所以我显然错过了一些东西。如何从第一个方法中获取productCap变量?

对此的任何解释都会很棒,谢谢!

3 个答案:

答案 0 :(得分:3)

你应该打电话给你的方法:

UI.println(capitalizeFirstLetter(product) + " from " + compan ...

答案 1 :(得分:1)

我认为不是这个

  UI.println(productCap + " from " + company + " is a premium brand prodcut and");

你想拥有这个

  UI.println(capitalizeFirstLetter(product) + " from " + company + " is a premium brand prodcut and");

答案 2 :(得分:0)

你可以按照以下方式调用你的方法

UI.println(capitalizeFirstLetter(product) + " from " + company + " is a premium brand prodcut and");

您的变量productCap是方法CapitalizaFirstLetter()的本地变量,因此无法在其他方法中访问。

要访问productCap的值,只需调用CapitalizeFirstLetter()方法,使其返回productCap的值。