如果我有一些IF語句,該如何返回1個值?如何在有多個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?
}
}
在整個方法中可以有多個return語句。 – Compass
一些替代方法:(1)在調用所選方法的位置返回字符串; (2)在方法的最外層範圍聲明String'test',並將這個* same *變量設置爲你的方法結果,無論你調用哪種方法。 –