Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I input in arrayList similar to array?

public void getDisMarks()
   {
       marks=new int[3];
       System.out.print("Enter marks of Physics: ");
       marks[0]=sc.nextInt();
       System.out.print("Enter marks of Chemistry: ");
       marks[1]=sc.nextInt();
       System.out.print("Enter marks of Maths: ");
       marks[2]=sc.nextInt();
}

So in this piece of code we are using array for 3 definite subjects. And we’re using scanner class to input from the user. Let’s say in the future I want to add a couple of more subject. So coding it again would not make it any flexible.

So I read that we could use arrayList, How can I use scanner class with arrayList similar to this piece of code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could do something like this:

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        List<Integer> list = new ArrayList<>();
        System.out.println("How many marks to enter?");
        int marksToEnter = sc.nextInt();

        for (int i = 0; i < marksToEnter; i++) {
            System.out.println("Enter next mark");
            list.add(sc.nextInt());
        }
        System.out.println(list);
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading