Leon schere
Leon schere

Reputation: 15

How to add as many elements as i want to an array list by an input?

How to add as many elements as I want to an array list - with only one insert operation?

I want to add 5 Items to a buy list with one input. And then I want to print the 5 items out.

This is what I have done now:

package paket1;

import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.JOptionPane;

public class Class2 {

    public static void main(String[] args) {

        int i = 0;

        while (i != 5) {

            String Eingabe = JOptionPane.showInputDialog("Add Einkaufsliste");

            ArrayList<String> einkaufsListe = new ArrayList<>();

            einkaufsListe.add(Eingabe);

        }
    }
}

Upvotes: 0

Views: 64

Answers (2)

jervi
jervi

Reputation: 160

Each time your iteration runs, you are creating a new, empty list, and adding one element to it. But this loop will never finish, because i is never incremented, and will always be 0. The correct code would look like this:

int i = 0;
List<String> einkaufsListe = new ArrayList<>();
while (i <= 5) {
    String eingabe = JOptionPane.showInputDialog("Add Einkaufsliste");
    einkaufsListe.add(eingabe);
    i++;
}

And then you will have to print it as well.

Upvotes: 1

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

I think it is better to extract this logic into separate method, that retrieves required list. If you want to use ArrayList, do not forget to set initial size.

public static List<String> gibAlleEinkaufe(int insgesamt) {
    List<String> einkaufsListe = new ArrayList<>(insgesamt);

    for(int i = 0; i < insgesamt; i++)
        einkaufsListe.add(JOptionPane.showInputDialog("Add Einkaufsliste"));

    return einkaufsListe;
}

Upvotes: 0

Related Questions