2

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 :)

3 Answers 3

2
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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Could I possibly add them in the initialization to avoid having to add them inside a method?
@user3128156 You can use a static initializer block (see my edit).
2

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));

Comments

0

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.