Is it possible in Java to redefine value after it already been defined(Like in JavaScript)? Take a look at my sample code, I am trying to redefine String array.
public String[] checkIfLengEnglish (){
String language = Locale.getDefault().getDisplayLanguage() ;
String LG = Locale.getDefault().getLanguage();
if(LG.contains("en")){
String language[] = {"English"}; // Redefining
}
else {
String Language[] = {"English/"+ Language,Language,"English"}; // Redefining
}
return Language[];
}
Language
in your code with multiple types at multiple scopes (once at the method level, twice in the if-block/else-block). Don't do that. []
to reference an array variable, don't do that. Since you declare the array inside the if-block, it only exists inside the if-block. To fix this, you need to declare it outside:
String[] languages; if( LG.contains("en")){ languages = new String[] {"English"}; }else { languages = new String[] {"English/"+ Language,Language,"English"}; } return languages;
Since you no longer use initalization (which can only happen when you declare a variable) but assignment, you need to use the "long form" for specifying the array values, which includes new String[]
.
Also note that as a general guideline, method and variable names should start with a lower-case letter and class/interface/enum names should start with a capital letter. That's not technically required, but following this guideline will make your code easier to understand for others.
Language[] is defined inside your if/else statement. You should try putting it above that like
String[] array = new String[];
if(true){
array = {"English"};
}
return array;
// dummy example
just reframing your code & variables for better understanding purpose
public String[] CheckIfLengEnglish (){
String displayLanguage = Locale.getDefault().getDisplayLanguage() ;
String LG = Locale.getDefault().getLanguage();
String arrayLanguages[];
if( LG.contains("en")){
arrayLanguages = {"English"};
}else {
arrayLanguages = {"English/"+ Language,Language,"English"};
}
return arrayLanguages ;
}
String[] Language=new String[];
if {
Language={"English"}
}
else {
String Language[] = {"English/"+ Language,Language,"English"}; }
return Language[] ;
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.