Search code examples
javastringtokenizertypecasting-operator

typecasting with StringTokenizer


I need to convert the output of nextToken() to type int and double. The way i'm doing it currently does not work and gives me the error saying java.lang.String cannot be converted to int. how else can this be done? Thank you!

     int id,age;
       String name;
       double gpa;
       String line = null;

  while( inputStream.hasNextLine())
   {
       line = inputStream.nextLine();
       size ++;

       StringTokenizer tokens  = new StringTokenizer(line," .,?\"");

       while(tokens.hasMoreTokens())
       {
          id = (int) tokens.nextToken();   //need to convert this
          name = tokens.nextToken();
          age =(int) tokens.nextToken();   //need to convert this 
          gpa = (double) tokens.nextToken();  //need to convert this
       }
   }

Solution

  • Try this:

    id = Integer.parseInt(tokens.nextToken());