【发布时间】:2017-02-28 21:56:47
【问题描述】:
如果我有一些 IF 语句,我如何返回 1 个值?
例如,当我选择 Shopify 时,它会调用一个新方法,该方法允许我在控制台中输入一些需要的凭据,然后将所有输入的数据附加到 1 个字符串中,并将该字符串(测试)返回给 Main 类。 如果我选择 Bigcommerce,它会调用几乎相同的方法,并将 Biggcomerce 所需的所有凭据也附加到 1 String(test2) 中。但在这种情况下, public String credentailsCollector() 应该返回 test2。
我该怎么做?谢谢。
public class CartCredentialsCollector {
//it should return something like this:
//store_url=https://test.myshopify.com&apiKey=myapikey&apiPassword=myapipassword
public String credentailsCollector() throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Do you want to connect a new shopping cart ('yes'/'no')");
String newConnection = bufferedReader.readLine();
if (newConnection.equals("no")) {
bufferedReader.close();
} else {
System.out.println("Specify your shopping cart. It works with Shopify and Bigcommerce only");
String newShoppingCart = bufferedReader.readLine();
if (newShoppingCart.equals("Shopify")) {
ShopifyCredentialsHandler sch = new ShopifyCredentialsHandler();
String test = sch.shopifyCredentialsHandler();
}
else if (newShoppingCart.equals("Bigcommerce")) {
BigcommerceCredentialsHandler bch = new BigcommerceCredentialsHandler();
String test2 = bch.bigcommerceCredentialsHandler()
}
else {
System.out.println("This method works with Shopify and Bigcommerce. Try to connect a Shopify or Bigcommerce store.");
bufferedReader.close();
}
}
// Here I need to return test (in case I choose "Shopify") or test2 (in case I choose "Bigcommerce"). How can I do that?
}
}
【问题讨论】:
-
您的方法中可以有多个返回语句。
-
一些替代方案:(1)在您调用所选方法的位置返回字符串; (2) 在方法的最外层声明 String
test,并将 same 变量设置为您的方法结果,无论您调用的是哪个方法。
标签: java string if-statement return-value