Question

I'm trying to do something that might seem simple do you but I'm kind of stuck and I can't wrap my head around how to do it.

So basically what I want to do is parse string str and create smaller strings and compare them to something in an if statement

    String str = ("1, 2, 3);
    StringTokenizer st = new StringTokenizer(str, ",");
    while (st.hasMoreElements()){
        //instead of printing the element I want to generate str[i] or something of the sort
        System.out.print(st.nextElemenet());
    }

    //then I want to do this as many times as I have str[i]
    if(str1 == 2 || str2 == 3 || str3 == 3){
    //do something
    }

Basically I want to parse a string, generate a bunch of smaller strings and use them in an if statement. Any ideas? Sorry if it seems like a simple question but I'm kind of stuck lol

PS Java 1.4 doesn't support .split and it needs to be in java 1.4 ^_^ I can make an ArrayList but I'm still not sure how to iterate through it in the if, comparing all the values of it with a given value. :/

Était-ce utile?

La solution

I think what you require is a String array.

String[] strArray = new String[st.countTokens()]; // Create an array with no. of tokens as the size
int counter = 0; // Counter variable to be used as the arrays index.
while (st.hasMoreElements()){
    //instead of printing the element I want to generate str[i] or something of the sort
    strArray[counter++] = st.nextElement(); // add the element to the array
}

This way you can add all the tokens to a String array and then you can traverse through this array and compare the elements. Now to do some if-checks on each of those elements you need a loop. I used the standard for loop since you're using Java 1.4.

for(int i=0; i<strArray.length; i++) {
    if(strArray[i].equals("someString")) { // use equals method for string value comparisons.
        // do something
    }
} 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top