N
N
Nikita Verdinsky2022-03-09 00:12:58
Java
Nikita Verdinsky, 2022-03-09 00:12:58

How to add data to ArrayList by constructor?

Good afternoon. Can you please tell me how to implement adding data by constructor to ArrayList?
class main

import java.util.*;

public class Main {

    public static void main(String[] args){
        ArrayList<Templates> list = new ArrayList<>();
        for(int i = 0; i<2; i++){
            System.out.println("Введите вопрос: ");
            Scanner scanner = new Scanner(System.in);
            Templates.questionText = scanner.nextLine();

            System.out.println("Введите ответ: ");
            Templates.answerText = scanner.nextLine();

            System.out.println("Укажите правильность ответа (true - верный, false - ложный): ");
            Templates.isAnswerCorrect = scanner.nextBoolean();

            list.add(new Templates(Templates.questionText, Templates.answerText, Templates.isAnswerCorrect));
        }
        for(int i = 0; i<2; i++){
            System.out.println(list.get(i));
        }
    }
}


Class Templates
public class Templates {

    public static String questionText;
    public static String answerText;
    public static boolean isAnswerCorrect;

    public Templates(String questionText, String answerText, boolean isAnswerCorrect){
        this.questionText = questionText;
        this.answerText = answerText;
        this.isAnswerCorrect = isAnswerCorrect;
    }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2022-03-09
@xez

import java.util.ArrayList;
import java.util.List;

public class CatsDemo {

    public static void main(String[] args) {
        Cat васька = new Cat("Васька");
        Cat мурзик = new Cat("мурзик");

        ArrayList<Cat> cats = new ArrayList<>();
        cats.add(васька);
        cats.add(мурзик);

        CatOwner catOwner = new CatOwner(cats);
    }
}

class Cat {
    private String name;

    public Cat(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

class CatOwner {
    private List<Cat> cats;

    public CatOwner(List<Cat> cats) {
        this.cats = cats;
    }

    public List<Cat> getCats() {
        return cats;
    }
}

So, I hope you understand?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question