0verflow
0verflow

Reputation: 1

Syntax error on token ";" ... why?

why is there syntax error on this line ( shown below ) ? Thanks

import java.util.StringTokenizer;

public class Tokenizer 
{           
   public Tokenizer()
   {
   }        

   int n;
   String esempio = "Ciao dodo sos";
   StringTokenizer Tok = new StringTokenizer(esempio); // <---- Syntax error on token ";"

   while (Tok.hasMoreElements())
      System.out.println("" + ++n +": "+Tok.nextElement());
}

Upvotes: 0

Views: 264

Answers (3)

Reimeus
Reimeus

Reputation: 159754

The compiler is attempting to associate the StringTokenizer declaration with the while loop so is expecting an opening brace { (for anonymous implementation block) rather than a semi-colon ;.

You need to use a method rather than have the code in the class block:

int n = 0;
String esempio = "Ciao dodo sos";
StringTokenizer Tok = new StringTokenizer(esempio); 

void doSomething() {

   while (Tok.hasMoreElements()) {
      System.out.println("" + ++n +": "+Tok.nextElement());
   }
}

A while statement is a non-declarative statement so it must appear in a method, static initializer or constructor.

Upvotes: 9

Frecklefoot
Frecklefoot

Reputation: 1692

What Reimeus said, plus a little more explanation on why you got the error on THAT line. With these two lines:

int n;
String esempio = "Ciao dodo sos";

you could have just been declaring class member data. When you actually tried to do something with the data, it became and error and needed to belong inside a method. HTH

Upvotes: 3

Jigar Joshi
Jigar Joshi

Reputation: 240880

You need to write statements inside method, or some applicable code block

Upvotes: 6

Related Questions