This is a snippet of my code:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Spiral3{
public static ArrayList<Integer> R = new ArrayList<Integer>();
public static ArrayList<Integer> K = new ArrayList<Integer>();
R.add(1);
K.add(1);
public static String pekare = "H";
All I'm trying to do here is create two arrays with the first element int 1
. So R = [1], K = [1]. I get the following error:
Spiral3.java:8: error: <identifier> expected
R.add(1);
^
Spiral3.java:8: error: illegal start of type
R.add(1);
^
Spiral3.java:9: error: <identifier> expected
K.add(1);
^
Spiral3.java:9: error: illegal start of type
K.add(1);
What's going on here? Thankful for your help :)
asked Mar 29, 2015 at 19:56
3 Answers 3
R.add(1);
K.add(1);
These statements should be inside some method or constructor or initializer block.
For example :
static {
R.add(1);
K.add(1);
}
answered Mar 29, 2015 at 19:57
If you want the list to be initialized to those values, you can pass it as List:
public static ArrayList<Integer> R = new ArrayList<Integer>(Arrays.asList(1));
public static ArrayList<Integer> K = new ArrayList<Integer>(Arrays.asList(1));
answered Mar 29, 2015 at 20:02
Comments
You should do like this;
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
answered Mar 29, 2015 at 20:07
Comments
lang-java