【问题标题】:How to include a returned string in another method - java如何在另一个方法中包含返回的字符串 - java
【发布时间】:2014-04-30 14:11:03
【问题描述】:

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

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 变量以包含在第二种方法中?

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

【问题讨论】:

  • productCap 只能在您的方法 capitalizeFirstLetter(String) 中访问。

标签: java string methods return


【解决方案1】:

你应该调用你的方法:

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

【讨论】:

    【解决方案2】:

    我认为不是这个

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

    你想要这个

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

    【讨论】:

      【解决方案3】:

      你可以如下调用你的方法

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-04
        • 2016-11-20
        • 2021-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多