0

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);
        }
    }
barbsan
  • 3,238
  • 11
  • 18
  • 27
Mikołaj K
  • 25
  • 4
  • you always add in index `0` increment your i and does filmExtended.setTytul(temp) return FilmExtended? – Akash Shah Jun 05 '19 at 09:04
  • Related [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/q/13102045) – Pshemo Jun 05 '19 at 09:08

4 Answers4

2

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

1

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

Marce
  • 480
  • 1
  • 6
  • 8
1
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);

} }
Vitaly
  • 115
  • 8
  • 1
    Could you explain what you changed? And why this solves the issue? Else your answer isnt that helpful, see [answer] thanks. – Zabuzard Jun 05 '19 at 10:24
0

Two ways to fix it:

  1. filmExtended.setTytul(temp) should return this.
  2. i++ or remove i
GirishB
  • 124
  • 5