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

  • 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.