简体   繁体   中英

Attempting to pass the nth specified element after splitting a String array

Good afternoon coders.

For the below I have this same XML Snippet

<E1EDP19 SEGMENT="1">
    <QUALF>001</QUALF> 
    <IDTNR>101-CB-PI</IDTNR> 
</E1EDP19>
<E1EDP19 SEGMENT="1">
    <QUALF>002</QUALF> 
    <IDTNR>101-CB-PI</IDTNR> 
    <KTEXT>OXY MED 0,47KG PI/J44.9/0201/97062</KTEXT> 
</E1EDP19>
<E1EDP19 SEGMENT="1">
    <QUALF>003</QUALF> 
    <IDTNR>6005919004334</IDTNR> 
</E1EDP19>
<E1EDP19 SEGMENT="1">
    <QUALF>006</QUALF> 
    <IDTNR>MEDLRG</IDTNR> 
</E1EDP19>

For every instance of QUALF being 002 I need to take KTEXT and split it by the /

I did this.

for (int i = 0; i < QUALF.length; ++i){ 
        if (QUALF[i].equals("002")){
            text = KTEXT[i];
         String segments[] = text.split("/");
         finalResult = segments[1];
         result.addValue(finalResult);
        }
}

However I would like access the 2nd element (segments[1]) in the first use of this code, ie. J44.9

In the 2nd use of this code I would need to access the 3rd element, ie. 0201

I get an arrayoutofbounds[1] exception currently. unless i alter the sample by making the

<E1EDP19 SEGMENT="1">
    <QUALF>002</QUALF> 
    <IDTNR>101-CB-PI</IDTNR> 
    <KTEXT>OXY MED 0,47KG PI/J44.9/0201/97062</KTEXT> 
</E1EDP19>

The 1st Instance.

You are using i for both the index into QUALF and KTEXT. This means that if QUALF[i]==002 is the 5th element, i will be 4 and you are out of bounds in KTEXT.

If I understand you right, you want to make a second index (j) that is initiated as 1, and increment j by 1 each time you are inside the IF.

for (int i = 0; i < QUALF.length; i++){ 
            if (QUALF[i].equals("002")){
                text = KTEXT[i];
                String[] parts = text.split("/");
                for (int j = 0; j < parts.length; j++){ 
                    if (j == 1){
                        String nthWord = parts[j];
                        result.addValue(nthWord);
                    }
                }
            }
}

Thanks people. As pointed out a 2nd loop within the initial to cater for the 2nd field argument.

This is then used to identify the 2nd element in the array by [j].

Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM