简体   繁体   中英

Java - Updating a string inside an if statement

The string postcode at the end is used as an input later on in my code and as you can see, it's hard-coded. What I want to do is make it more dynamic. So boolean pc4 is set to the countries that accept 4-digit postcodes. pc5 is 5-digit and pc6 6-digits.

What I want to do is something like:

if(pc4==true){String postcode="1234"}

As you guys already know, this doesn't work outside the if-statement.

So my question is: can I update a string outside an if-statement or is there more efficient way of getting to where I need to be?

String state1 = "state";

 boolean pc4 = (bString.equals("Bahrain") || bString.equals("Afghanistan") 
             || bString.equals("Albania") || bString.equals("Armenia") 
             || bString.contains("Australia")
             ... 
             || bString.equals("Tunisia") ||bString.equals("Venezuela") );
 boolean pc5 = (bString.equals("Alan Islands") || bString.equals("Algeria")
             || bString.equals("American Samoa") || bString.equals("Wallis and Futuna") 
             ...
             || bString.equals("Zambia"));
 boolean pc6 = (bString.equals("Belarus") || bString.equals("China")
             || bString.equals("Colombia") || bString.equals("India")
             ...
             || bString.equals("Turkmenistan") || bString.equals("Viet Nam"));

 String postcode = "123456";

Define postcode outside the block and assign value to it based on condition.

Something like below:

  String postcode="";


 if(pc4){postcode="1234"}

While tangential to your original question, rather than having gigantic one-line if statements, it might be easier to use a Map to define the length of your postal codes.

HashMap<String, Integer> countries = new HashMap<>();
countries.add("Bahrain", 4);

switch(countries.get(myCountry)) {
  case 4:
    // Stuff!
}

使用三元条件运算符。

String postcode = pc4 ? "1234" : "";
String postcode = null; // or ""
if (pc4)
  postcode = "1234";
else if (pc5)
  postcode = "12345";
else if (pc6)
  postcode = "123456";
else
  postcode = "default value";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM