hasMoreElements () in StringTokenizer returns true only

1

Good morning. I have the following code in java, I am developing an Android application. The code is:

    bajaRepostajeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            String repostajeString = bajaRepostajeSpinner.getItemAtPosition(i).toString();
            StringTokenizer st = new StringTokenizer(repostajeString, "\t");
            int k = 0;
            while (st.hasMoreElements()){
                switch (k){
                    case 0:
                        establecimiento.setNombreEstablecimiento(token.nextToken());
                        break;
                    case 1:
                        repostaje.setPrecioTotal(Double.parseDouble(token.nextToken()));
                        break;
                    case 2:
                        vehiculo.setMarca(token.nextToken());
                        break;
                }
                k++;
            }

The fact is that once it enters the while loop, it never leaves it, I also tried with hasMoreTokens() and the result remains the same. Could someone tell me the mistake I'm making? Thanks in advance.

    
asked by Alberto Méndez 24.05.2017 в 11:05
source

2 answers

3

Once inside the loop you have to call nextElement() or nextToken() to go to the next element. In your case if k is 3 or more, it would never pass to the next element, and therefore it would only pass 3 times to the next element (in the cases of 0 , 1 and 2 ).

while (st.hasMoreElements()){
    switch (k){
        case 0:
            establecimiento.setNombreEstablecimiento(token.nextToken());
            break;
        case 1:
            repostaje.setPrecioTotal(Double.parseDouble(token.nextToken()));
            break;
        case 2:
            vehiculo.setMarca(token.nextToken());
            break;
        default:
            st.nextElement();
    }
    k++;
}
    
answered by 24.05.2017 / 11:14
source
1

The problem seems to be caused by a k that is not 0, 1, or 2. In that case it would not be done nextToken, it would not be advanced, and there would always be more elements, since the next one is never advanced.

Note: nextElement is the same but returning Object, is the method of the StringTokenizer parent interface, and therefore also consumes an element. The answer of @cnbandicoot is therefore wrong.

    
answered by 24.05.2017 в 11:24