1.Expected output:
The input is a string, the expected output is an int array.
For examples:
(1) input: a string, such as "1234";
=> output: int array: {1,2,3,4}
(2) input: "12s4"
=> output: throw out an Exception.
2.My code:
I'm converting the input string to an int array as the following:
int[] StringToArray(String strInput) {
int[] nArray = new int[strInput.length()];
for(int i=0; i<strInput.length(); i++) {
nArray[i] = Character.digit(strInput.charAt(i), 10);
}
return nArray;
}
But when the input is a character, the output can still be converted to an integer.
For example, "12s4" is converted to be [1,2,-1,4].
3.Question:
How can it throw out an Exception if there is a character such as 's' in the input string?
Thank you.
question from:
https://stackoverflow.com/questions/65951151/how-to-throw-exception-as-converting-a-string-to-an-int-array-in-java 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…