javaarraysstringinputinteger

Convert String input to int array in Java


How do I convert a numeric string input from a user into an integer array in Java?

What I did so far is:

# Get User input
System.out.println("Guess the number: ");
String input = read.nextLine();

# String to int
int digitNumber = Integer.parseInt(input);

I'm trying to convert a numeric string (e.g., "089") entered by a user into an integer array where each digit becomes an individual element. For example, "089" should result in [0, 8, 9]. However, using Integer.parseInt(input) just gives me 89 and drops the leading zero.

What would be the best way to convert this input into an array of integers?


Solution

  • tl;dr

    int[] numbers = 
        input
            .codePoints()                        // Generate a stream of code point `int` numbers for the characters in this string.
            .filter ( Character :: isDigit )     // Ignore any non-digit.
            .mapToObj ( Character :: toString )  // Convert each `int` code point to its character. We expect that character to be a digit.
            .mapToInt ( Integer :: parseInt )    // Parse the textual digit as an `int` primitive value.
            .toArray ();                         // Collect those `int` primitive values into an array, `int[]`. 
    

    Avoid char

    The Answer by Stultuske is correct, except that you should avoid using char type.

    The char type has been essentially broken since Java 2, and legacy since Java 5. As a 16-bit value, char is physically incapable of representing most characters.

    Use code points

    Make a habit of using integer code point numbers rather than char values.

    Calling String#codePoints generates an IntStream of int primitive values, one int for each character in that string successively.

    String input = "089" ;
    int[] codePoints = input.codePoints().toArray() ;
    int[] numbers = new int[ codePoints.length ] ;
    int index = 0 ;
    for ( int codePoint : codePoints ) 
    {
        String digit = Character.toString ( codePoint ) ;
        int number = Integer.parseInt ( digit ) ;
        numbers [ index ] = number ;
        index = index + 1 ;
    }
    System.out.println ( Arrays.toString( numbers ) ) ;
    

    See this code run at Ideone.com.

    [0, 8, 9]

    Verify digit

    As Rob Spoor reminds us in a Comment, we should verify that each input code point does indeed represent a digit.

    You could check for just the Latin 0-9 digits, or more expansively check for any script’s digits.

    String input = "0Z9" ;  // Simplate FAULTY INPUT.
    int[] codePoints = input.codePoints().toArray() ;
    int[] numbers = new int[ codePoints.length ] ;
    int index = 0 ;
    for ( int codePoint : codePoints ) 
    {
        String digit = Character.toString ( codePoint ) ;
        if ( Character.isDigit ( codePoint ) )  // Verify the code point does indeed represent a character that is a digit.
        {
            int number = Integer.parseInt ( digit ) ;
            numbers [ index ] = number ;
            index = index + 1 ;
        }
        else 
        {
            System.out.println ( "ERROR - Received non-digt. Code point: " + codePoint + ". Character: " + digit ) ;  
        }
    }
    System.out.println ( Arrays.toString( numbers ) ) ;
    

    See this code run at Ideone.com.

    Notice this throws off our assumption in sizing our results array.

    ERROR - Received non-digt. Code point: 90. Character: Z

    [0, 9, 0]

    Modern Java

    Using a List rather than an array would help remedy that issue. And using modern Java we can further simplify this code.

    String input = "0Z89" ;  // Simulate FAULTY INPUT.
    
    int[] numbers = 
        input
            .codePoints()                        // Generate a stream of code point `int` numbers for the characters in this string.
            .filter ( Character :: isDigit )     // Ignore any non-digit.
            .mapToObj ( Character :: toString )  // Convert each `int` code point to its character. We expect that character to be a digit.
            .mapToInt ( Integer :: parseInt )    // Parse the textual digit as an `int` primitive value.
            .toArray ();                         // Collect those `int` primitive values into an array, `int[]`. 
            
    System.out.println ( Arrays.toString( numbers ) ) ;
    

    When run at Ideone.com:

    [0, 8, 9]