Reputation: 13
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";
Upvotes: 0
Views: 1858
Reputation: 2698
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!
}
Upvotes: 2
Reputation: 66637
Define postcode
outside the block and assign value to it based on condition.
Something like below:
String postcode="";
if(pc4){postcode="1234"}
Upvotes: 6
Reputation: 14086
Use the ternary conditional operator.
String postcode = pc4 ? "1234" : "";
Upvotes: 1
Reputation: 10047
String postcode = null; // or ""
if (pc4)
postcode = "1234";
else if (pc5)
postcode = "12345";
else if (pc6)
postcode = "123456";
else
postcode = "default value";
Upvotes: 0