Napisałem metodę, która ma znajdować pierwszą liczbę typu integer w otrzymanym tekście.
Proszę o ocenę. Czy kod wygląda i działa dobrze ?
Co powinienem zmienić, żeby wyglądało i działało dobrze....
public class MoreUtils {
/*
* The method searches the first positive integer in the text.
*/
public static int findInt(String s) {
int[] arr = new int[10]; //The number 2,147,483,647 is the maximum positive value for integer, it has 10 digits.
int index = 0;
/*
* Extracts the first 10 found digits.
*/
int excludeZero = 1; //Indicates that the first digit greater than zero was found. 1 - exclude zero 0 - join zero.
for(int i=0;i< s.length();i++) {
if((int)s.charAt(i)>=(48+excludeZero)&&(int)s.charAt(i)<=57) {
arr[index]=(int)s.charAt(i)-48;
index++;
excludeZero=0;
}
if(index>9) break;
}
/*
* Converts the found digits to a number.
*/
long n = 0; //For case if the number is greater than 2,147,483,647 we change later to integer.
int k =index;
for(int i=0;i<index;i++) {
int m = 1;
k--;
for(int j=k;j>0;j--) {
m=m*10;
}
n = n+m*arr[i];
}
return (n>Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int)n;
}
public static void main(String args[]) {
System.out.println(findInt("a1b2c3m4567M8"));
System.out.println(findInt("m2223M"));
System.out.println(findInt("21474836470"));
System.out.println(findInt(""));
System.out.println(findInt(" 1"));
System.out.println(findInt("\\2 \0\1\2 \\"));
System.out.println(findInt("0000003456789"));
}
}