Smo
Smo

Reputation: 41

How to split a String into integers?

I'd like to split a String, and store each digit of the String into an integer.

Here's my test code:

public class test {
    public static void main(String[] args){
        int firstGuessDigit, secondGuessDigit, thirdGuessDigit, fourthGuessDigit;
        String guess = "1234";
        String[] parts = guess.split("\");
        firstGuessDigit = Integer.parseInt(parts[0]);
        secondGuessDigit = Integer.parseInt(parts[1]);
        thirdGuessDigit = Integer.parseInt(parts[2]);
        fourthGuessDigit = Integer.parseInt(parts[3]);
    }

}

When I run the program, I get an error: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at test.main(test.java:11)

Upvotes: 1

Views: 5924

Answers (5)

user12486737
user12486737

Reputation: 1

("%-11s%03d%n")% : used as a formatter.

  • -: minus sign used for left indentation of the string.
  • 11s: here 11 denotes the string's minimum field width 11.
  • 0: pads the extra 0s in the integer.
  • 3d: here 3 denotes integer's minimum field width 3.
  • %n: prints the new line.

Hope, this helps!

Upvotes: 0

StackFlowed
StackFlowed

Reputation: 6816

The error you getting is because you are trying to do parts[1] when it doesn't have it.

Code you are looking for is:

String guess = "1234";
int[] guessInteger = new int[guess.length()];
int i=0;
for(Character ch : guess.toCharArray()){
    if(Character.isDigit(ch)){
        guessInteger[i++] = Character.getNumericValue(ch);
    }
}

Upvotes: 2

cozla
cozla

Reputation: 137

This should do it.

public class Test {

    public static void main(String[] args) {

        int firstGuessDigit, secondGuessDigit, thirdGuessDigit, fourthGuessDigit;
        String guess = "1234";

        String[] parts = new String[4];
        for(int i = 0; i < 4; i++) {
            parts[i] = ""+guess.charAt(i);
        }

        firstGuessDigit = Integer.parseInt(parts[0]);
        secondGuessDigit = Integer.parseInt(parts[1]);
        thirdGuessDigit = Integer.parseInt(parts[2]);
        fourthGuessDigit = Integer.parseInt(parts[3]);

    } 

}

Upvotes: 0

David Conrad
David Conrad

Reputation: 16359

You can get the characters of the string using the chars() stream and map them to their numeric values with Character.getNumericValue:

"1234".chars().map(Character::getNumericValue).toArray()

If you prefer to get them as a list instead of an array, you can use:

"1234".chars().map(Character::getNumericValue).boxed().collect(Collectors.toList())

Upvotes: 2

AntonH
AntonH

Reputation: 6437

You can use String#toCharArray instead:

char[] parts = guess.toCharArray();
firstGuessDigit = Integer.parseInt(Character.toString(parts[0]));
secondGuessDigit = Integer.parseInt(Character.toString(parts[1]));
thirdGuessDigit = Integer.parseInt(Character.toString(parts[2]));
fourthGuessDigit = Integer.parseInt(Character.toString(parts[3]));

Upvotes: 1

Related Questions