I got a two dimensional String array with only numbers in it;
System.out.println(Arrays.deepToString(temp));
[[1, 3, 1, 2], [2, 3, 2, 2], [5, 6, 7, 1], [3, 3, 1, 1]]
I need to check if the array contains only numbers, otherwise I will throw an exception.
System.out.println(Arrays.deepToString(temp[0]).matches("[0-9]*")); - return false
System.out.println(Arrays.deepToString(temp[0]).matches("[0-9]+")); - return false
As far as I get, The code says that the array does not contains only numbers, because when converted to char the array is like :
[[, [, 1, ,, , 3, ,, , 1, ,, , 2, ], ,, , [, 2, ,, , 3, ,, , 2, ,, , 2, ], ,, , [, 5, ,, , 6, ,, , 7, ,, , 1, ], ,, , [, 3, ,, , 3, ,, , 1, ,, , 1, ], ]]
How can I check if it contains only numbers?
You should first loop through your array. Since each element will be an array, loop through it. Then for each element (that should be a String) check if it's what you want.
To loop through your Array of arrays :
boolean arrayIsCorrect = true; //flag to know if array is correct
for(int i=0; i<array.length; i++) { //loop through the array of arrays
for(int j=0; j<array[i].length; j++) { //loop through the sub-array array[i]
if(!isCorrect(array[i][j])) {
arrayIsCorrect = false;
break; //optimization not required
}
}
if(!arrayIsCorrect) { //optimization not required
break;
}
}
System.out.println("Is the array correct ? " + arrayIsCorrect ); //print the result
In your question it's not clear if you want elements to be digit or numbers. In case of digit the function isCorrect()
should look like :
public boolean isCorrect(String s) {
return s.matches("[0-9]");
}
In case of number, check this answer
I would make a function that checks if it is numeric.
Something like this:
for(int i = 0; i < array.size();i++){
for(int j = 0; j < array.size();j++){
if(temp.isNumeric(temp[i][j] == false)
break;
}
}
public static boolean isNumeric(String value) {
boolean result;
try {
Integer.parseInt(value);
result = true;
} catch (NumberFormatException excepcion) {
result = false;
}
return result;
}
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.