2

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?

6
  • 1
    Iterate over each char and convert each char into an int. Commented Jun 26 at 6:09
  • 1
    So you just like to split() the numerical string into single digits? Commented Jun 26 at 6:09
  • Yes, that's what I want. Thanks for the previous comment, I found that I can use Character.getNumericValue(input.charAt(i)). Commented Jun 26 at 6:14
  • For String s, you can do int[] a = s.codePoints().map(Character::getNumericValue).toArray(); Commented Jun 26 at 7:03
  • If you are developing some kind of mastermind game, then you just need to compare the characters of the string entered by the user. If you want to ensure that the user enters only digits, then call method nextInt, of class java.util.Scanner, rather than method nextLine. Commented Jun 26 at 7:29

2 Answers 2

4

Integer.parseInt(input);

will convert the ENTIRE input (not char by char) into a numerical (int) value, so if your input is "089", 89 is the correct (and to be expected) result.

If you want the result to be

[0, 8, 9]

you'll need to run the parseInt method not on input "089", but on inputs "0", "8", "9".

Step 1: turn your original input String in an array of chars
Step 2: iterate over that array of chars, and run Integer.parseInt(String.valueOf(tmpChar));

Why the 'valueOf' ? Because Integer.parseInt doesn't accept char as input.

Sign up to request clarification or add additional context in comments.

1 Comment

You can use Character.digit(tmpChar, 10) instead of Integer.parseInt as long as you check the result, and handle a -1 return value.
1

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]

2 Comments

The modern Java approach appears significantly more concise and easier for me to comprehend. In comparison to the traditional style, is this generally considered a more contemporary practice and recognized as an industry standard?
@its.spark.dev Regarding “more contemporary”, yes in that functional programming features (lambdas, method references, streams) were added to Java later. Regarding “industry standard”, no there is no standard for this. Use the functional approach where it makes your code simpler, clearer, and less error-prone. Otherwise use conventional imperative approach. Also, know that streams may be a tad slower than conventional looping, though not significantly so in common business apps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.