A Percentage of Refactoring
by in CodeSOD on 2025-10-21Joseph was doing a refactoring effort, merging some duplicated functions into one, cleaning up unused Java code that really should have been deleted ages ago, and so on. But buried in that pile of code that needed cleaning up, Joseph found this little bit of code, to validate that an input was a percentage.
@Override
public Integer validatePercent(final String perc, final int currentPerc){
char[] percProc= perc.toCharArray();
char[] newPerc = new char[perc.length()];
int percent=0;
int y=0;
if(percProc.length>4){
return -1;
}
for(int x=0;x<percProc.length;x++){
if(Character.isDigit(percProc[x])){
newPerc[y]=percProc[x];
y++;
}
}
if(y==0){
return -1;
}
String strPerc=(new String(newPerc));
strPerc=strPerc.trim();
if(strPerc.length()!=0){
percent=Integer.parseInt(strPerc);
if(percent<0){
return -1;
}else if(percent>100){
return -1;
}else if(Integer.parseInt(strPerc)==currentPerc){
return -1;
}else{
return Integer.parseInt(strPerc);
}
}else{
return-1;
}
}