-2

The following code I have spent several hours on using multiple different strategies for extracting the integer values from the String st and getting them into their own int variables.

This is a test program, the actual assignment that I am working on requires me to build a class that will make another program ( program5 ) run correctly. The string generated by program5 could contain more than just three integers, but all will be seperated by a space. Because of the specifics of the assignment I am not allowed to use arrays, or regex because we have not covered them in class.

As of right now I can't even get it to print out all of the three integers I have in my test string. If anyone sees anything wrong with my syntax or problems with my logic please let me know!

public class test {

public static void main(String[] args){


    String st = "10 9 8 7 6";
    int score;
    int indexCheck = 0;
    String subSt;

            for(int i=0; i <= st.length(); i++)
            {
                if(st.indexOf(' ') != -1)
                {
                    if(st.charAt(i) == ' ')
                    {
                        subSt = st.substring(indexCheck, i);
                        score = Integer.parseInt(subSt);
                        indexCheck = st.indexOf(i);
                        System.out.println(score);
                    }
                }
                else
                {
                    subSt = st.substring(st.lastIndexOf(" "));
                    score = Integer.parseInt(subSt);
                    System.out.println(score);
                }
            }
}

}

Dirk Lachowski
  • 3,121
  • 4
  • 40
  • 66
DustinR
  • 26
  • 1
  • 3
  • 5
    [Homework night eh](http://stackoverflow.com/questions/26413608/splitting-a-string-into-multiple-int-form-using-indexof)? – Boris the Spider Oct 16 '14 at 21:09
  • If you are not allowed to use arrays, your input can contain an arbitrary number if ints and you have to store them in distinct vars - how should this fit together? – Dirk Lachowski Oct 16 '14 at 21:25
  • `int[] ints = Pattern.compile("\\s+").splitAsStream(st).mapToInt(Integer::parseInt).toArray();` – David Conrad Oct 16 '14 at 21:52

1 Answers1

3

Use st.split(" ") to get a String[] that stores the string split by spaces, and then use Integer.parseInt(array[0]) on each index to to convert it to an int.

Example

String str = "123 456 789";
String[] numbers = str.split(" ");
int[] ints = new int[numbers.length];
for(int c = 0; c < numbers.length; c++) ints[c] = Integer.parseInt(numbers[c]);
SamTebbs33
  • 5,507
  • 3
  • 22
  • 44