-1

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.

Community
  • 1
  • 1
Demeter
  • 13
  • 3
  • Don't assume that just because it has `Array` in the name that it is one. Arrays have built-in syntax to read and write to a certain index, whereas an `ArrayList` is a class like any other. You need to use a different method to read than to write, and there are several for each. `set()` and `add()` are the most notable, as well as `remove()`. – bcsb1001 Feb 22 '16 at 22:25

1 Answers1

5

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>();
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523