Search code examples
javaarraysarraylistmethodsaddition

Add Element to ArrayList


I´m pretty new to coding. I have a method "einkaufen" where the user is asked to chose a Product. For each choice there is a switch case that asks if he wants to buy the product. If the user types "ja", I want to add the item´s price to an ArrayList "einkaufsliste" I created in the beginning.

But Eclipse is giving me an Error that says "einkaufsliste cannot be resolved".

How can I fix this?

//List with prices:
double [] waren = new double[5];
        waren[0] = 0.00;
        waren[1] = 2.49;
        waren[2] = 2.79;
        waren[3] = 0.79;
        waren[4] = 2.99;

//List to add to:
ArrayList<Double>einkaufsliste = new ArrayList<Double>();
        einkaufsliste.add(0.00);   **//right here i can eaysily add a value to the list**

//Method:
public static void einkaufen(double waren[]) {

        int n;
        String kaufen = "ja", x;
        boolean wareKaufen = true, wareNichtKaufen = false;

        System.out.println("Welche der angebotenen Waren möchtest du kaufen?");
        System.out.println("Angebot: \t1: Kinderriegel");
        System.out.println("Angebot: \t2: Nutella");
        System.out.println("Angebot: \t3: Wasser");
        System.out.println("Angebot: \t4: CDs");

        Scanner nutzerWare = new Scanner(System.in);
        n = nutzerWare.nextInt();

        switch (n) {
        case 1:
            System.out.println("Deine Auswahl: Kinderriegel \tPreis: " + waren[n] + "\nMöchtst du diese Ware zu deinem Einkaufswagen hinzufügen?");
            Scanner kinderriegelKaufen = new Scanner(System.in);
            x = kinderriegelKaufen.nextLine();
            if(x.equals(kaufen)) {
                wareKaufen=true;
                System.out.println(wareKaufen);             
                einkaufsliste.add(waren[n]);    **//ERROR right here I want to add the Item to the List but it´s not working**
                } else {
                    wareKaufen = false;
                    System.out.println(wareNichtKaufen);    
                }
            break;

Solution

  • Since the Problem had to do with the static and I couldn´t simply add a static infront of my ArrayList, I simply deleted the List from the main method and created it outside of any method. Not sure if it´s the right way, but for now it works. Thanks for the Help!