Syntax error on token ";", { expected after this token in Random string creator

user2615699 picture user2615699 · Sep 16, 2013 · Viewed 52.5k times · Source

I am writing code to generate a random 3 letter strings using the letters a, b, and c. I am getting the error message "Syntax error on token ";", { expected after this token" after the line where i create the random variable (Random rand = new Random();). I do not know why I am getting this error when it looks fine to me.

I am also getting the error message: Syntax error, insert "}" to complete ClassBody, after the last bracket in the program. I am almost postive all my closing brackets match up so I do not know where this error is coming from. PLEASE HELP!!

 import java.util.*;


 public class Orders {

String alphabet = "abc";
ArrayList<String> list = new ArrayList<String>();
int n = alphabet.length();

Random rand = new Random();
for (int i = 0; i < 10000; i++){
    char a = alphabet.charAt(rand.nextInt(n));
    char b = alphabet.charAt(rand.nextInt(n));
    char c = alphabet.charAt(rand.nextInt(n));

    String s = Character.toString(a) + Character.toString(b) + Character.toString(c); 

    if(list.indexOf(s) == -1){
        list.add(s);
    }
}
 system.out.println(arrayList);
}

Answer

Juned Ahsan picture Juned Ahsan · Sep 16, 2013

In Java, you cannot directly write the executable statements in class. You need to move your code in a method. Only variables declaration is allowed outside the method/blocks. Just for the sake of testing, ,move everthing to main method. Try this:

  public class Orders {

        public static void main(String argsp[]) {
            String alphabet = "abc";
            ArrayList<String> list = new ArrayList<String>();
            int n = alphabet.length();

            Random rand = new Random();
            for (int i = 0; i < 10000; i++){
               char a = alphabet.charAt(rand.nextInt(n));
               char b = alphabet.charAt(rand.nextInt(n));
               char c = alphabet.charAt(rand.nextInt(n));

               String s = Character.toString(a) + Character.toString(b) + Character.toString(c); 

               if(list.indexOf(s) == -1){
                   list.add(s);
               }
            }
            System.out.println(list);
        }

}

Note: system.out.println(arrayList); will throw an error because there is no varaible called arrayList, i think it should be replaced with variable list. Also system should be System.