Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

How to throw exception as converting a string to an int array in Java?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use String#matches here to assert that no character be a non digit:

int[] StringToArray(String strInput) throws Exception {
    if (!strInput.matches("\d+")) {
        throw new Exception("Invalid input contains non digits");
    }

    int[] nArray = new int[strInput.length()];
    for (int i=0; i < strInput.length(); i++) {
        nArray[i] = Character.digit(strInput.charAt(i), 10);
    }

    return nArray;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...