Mikołaj K
Mikołaj K

Reputation: 35

Cannot add a class field to ArrayList

I have no idea how to properly write line of code adding class field to an ArrayList

public class Main {
    public static void main(String[] args) throws IOException
    {
        zapisz("BazaDanych.txt");
        Scanner scanner = new Scanner(System.in);
        FilmExtended filmExtended = new FilmExtended();
        ArrayList<FilmExtended> bazaFilmow = new ArrayList<>();
        int i = 0;
        while(scanner.nextInt()!= 0)
        {
            boolean check = true;
            do
            {
                System.out.println("Podaj tytuł fimu: ");
                String temp = scanner.nextLine();
                if (temp.matches("[a-zA-Z]{2,}"));
                {
                    bazaFilmow.add(i,filmExtended.setTytul(temp));
                    check = false;
                }
            }while (check);
        }
    }

Upvotes: 0

Views: 84

Answers (4)

Vitaly
Vitaly

Reputation: 115

public class Main {
public static void main(String[] args) throws IOException
{
    zapisz("BazaDanych.txt");
    Scanner scanner = new Scanner(System.in);
    List<FilmExtended> bazaFilmow = new ArrayList<>();
    //remove index
    while(scanner.nextInt() != 0)
    {
        boolean check = true;
        do
        {
            System.out.println("Podaj tytuł fimu: ");
            String temp = scanner.nextLine();
            if (temp.matches("[a-zA-Z]{2,}"));
            {
                FilmExtended filmExtended = new FilmExtended(); //create new instance
                filmExtended.setTytul(temp);
                bazaFilmow.add(filmExtended); //use add without index or else need to increment your index
                check = false;
            }
        } while (check);

} }

Upvotes: 1

GirishB
GirishB

Reputation: 144

Two ways to fix it:

  1. filmExtended.setTytul(temp) should return this.
  2. i++ or remove i

Upvotes: 0

user8007559
user8007559

Reputation:

You don't increment your index i. It's always 0. You have to put i++; in your do while loop

Upvotes: 2

Marce
Marce

Reputation: 477

You have to add i++; in the do while loop

Upvotes: 1

Related Questions