I'm trying to take a string of a number i.e. 123456 of any size and then convert each int in the string to an int to be added to a linked list. I.E.
read 1 convert to int then add to linked list, read 2 convert to int then add to linked list, etc. I can't figure out a way to read an individual int in the string. I can parse the whole string to an int but thats not what I want. Not sure if the .split() for strings will work here because there is no pattern and I need to accept negatives and decimal fractions. I tried messing around with a char array but didn't see any way to convert from char to int. Here is my snippet:

It's a little funky looking from me just trying the Char array but it's what I have. Any input/thoughts on where to go from here would be great. Thanks.

public void accept(String str){
        int i = 0;
        char[] temp = new char[i];
        for(i = 0; i < str.length(); i++){
            str.getChars(i, i, temp, i);
            int val = Character..parseInt(temp[i]);
            insertLow(val);
                    }
        System.out.println("The string is " + toString());

    }

I may be going about this in the entirely wrong way and if I am please say so lol. Here is what I have revised my first posted code. I'm getting an ArrayIndexOutOfBoundsException at this line.

str.getChars(i, i+1, temp, i);

Here is my revised code:

public void accept(String str){
        int i = 0;
        String charCon;
        char[] temp = new char[i];
        for(i = 0; i < str.length(); i++){
            str.getChars(i, i+1, temp, i);
            charCon = Character.toString(temp[i]);
            int val = Integer.parseInt(charCon);
            insertLow(val);
                    }
        System.out.println("The string is " + toString());

    }

Just use a for loop that cycles through the entire String one character at a time.

for (int i = 0; i < string.length(); i++){
1. get the current character
2. attempt to parse this character into an integer.
3. add the integer you just parsed into the linked list.
}

For step 1, see the String class documentation's charAt method. http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html

For step 2, you could use the Integer.parseInt method - there is a better way I think - but that would effective also.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.