Search code examples
javaexceptionstringtokenizer

Java StringTokenizer Error when outputting to console


I'm trying to use the class StringTokenizer to split a character string from a text file, but when I'm running the app, the compiler prints in the Netbeans console the words that I'm splitting but also shows an exception.

This is my code:

package Calqfunny; 

import java.io.BufferedReader; 
import java.io.FileReader;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;

public class Files {

public String direccion;

public Files(){

    direccion = " ";
}

public Files(String direccion){

    this.direccion = direccion;
}




public String leerTxt(String direccion){

    String auxiliar = " ";

    try{

        BufferedReader br = new BufferedReader(new FileReader(direccion));
        String temp = " "; //Aqui guardamos el texto del archivo temporalmente
        String banana; //aqui almacenamos 


        while((banana = br.readLine())!=null){
            //se realiza el ciclo mientras que el archivo tenga datos.

           temp = temp + banana; 

        }
        auxiliar = temp;

    }catch(Exception e){

    JOptionPane.showMessageDialog(null,"\"¿Cómo vas a pedir un archivo que no existe? :v\"");

    }

    String nombre = null, apellido = null, edad = null, bday = null;
   StringTokenizer tokens = new StringTokenizer (auxiliar, ";");

    System.out.println("Nombre\tApellido Edad\tFecha de Nac.");
    while(tokens.hasMoreTokens()){


          nombre = tokens.nextToken();
          apellido = tokens.nextToken();
          edad = tokens.nextToken();
          bday = tokens.nextToken();


          System.out.println(nombre+"\t"+apellido+"\t"+edad+"\t"+bday);

    }

        return auxiliar;
  } 
}

This is the output from my app

Nombre  Apellido  Edad  Fecha de Nac.
David    Villa     31        1985
Andrea   Pirlo     36        1980
Lionel   Messi     29        1987
Tomas    Rincon    27        1989

And this is the exception that the compiler throws

Exception in thread "main" java.util.NoSuchElementException

at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)

at Calqfunny.Files.leerTxt(Files.java:69)

at Calqfunny.Mein.main(Mein.java:14)

C:\Documents and Settings\Goyo\Configuración local\Datos de    
programa\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned:1

BUILD FAILED (total time: 0 seconds)

What can I do to solve it?


Solution

  • Your while loop is testing if the StringTokenizer has ONE more token. But then you are reading FOUR more tokens. This is going to crash when the number of tokens is not divisible by four.

    What you can safely do is:

    StringTokenizer tokens = new StringTokenizer(auxiliar, ";");
    
    while(tokens.hasMoreTokens()){
        token = tokens.nextToken();
        System.out.println(token);
    }