I'm having trouble with creating an Arraylist
in a new class (I'm using the DrJava IDE). The assignment is to create a constructor with n
lottery tickets numbered from 1 to n
.
import java.util.ArrayList;
public class Tombola {
private ArrayList<Integer> arr;
public Tombola(int n){
for (int i = 0; i < n-1; i++){
this.arr.add(i) = i + 1;
}
}
}
The error I get is:
unexpected type.
required: variable.
found: value.
I've tried to change n
and i
to integer, but it didn't help.
This is incorrect:
this.arr.add(i) = i + 1;
add(...)
method does not provide you with a target for an assignment, so assigning it i+1
would not work. Instead, you should add i+1
, like this:
this.arr.add(i + 1);
You have two additional errors in your code:
1: this loop
for (int i = 0; i < n-1; i++)
will iterate n-1
times, not n
times. To get n
iterations use
for (int i = 0; i < n; i++) // <<== This is most common
or
for (int i = 0; i <= n-1; i++) // <<== This is less common
2: your array list is not initialized. You need to change its declaration as follows:
private ArrayList<Integer> arr = new ArrayList<Integer>();
or even to
private List<Integer> arr = new ArrayList<Integer>();