mrt181
mrt181

Reputation: 5316

Constructor parameter is an array of objects

I have a class with this constructor:

Artikel(String name, double preis){
    this.name = name;
    verkaufspreis = preis;
    Art = Warengruppe.S;

I have a second class with this constructor:

Warenkorb(String kunde, Artikel[] artikel){
    this.kunde = kunde;
    artikelliste = artikel;
    sessionid = s.nextInt();
    summe = 0;
    for(Artikel preis : artikel){
        summe += preis.verkaufspreis;
    }
}

How do i get an Artikel into the Warenkorb and the artikelliste array?

Upvotes: 0

Views: 287

Answers (4)

Andreas Dolk
Andreas Dolk

Reputation: 114767

And, looks like you're using Java 1.5+ anyway, try this alternative for Warenkorb:

Warenkorb(String kunde, Artikel...artikel){
        this.kunde = kunde;
        artikelliste = artikel;
        sessionid = s.nextInt();
        summe = 0;
        for(Artikel preis : artikel){
                summe += preis.verkaufspreis;
        }
}

Written like this, you can get rid of the ugly Array notation and construct a Warenkorb like this:

new Warenkorb("Dieter", new Artikel("Kartoffel", 0.25)};
new Warenkorb("Günther", new Artikel("Kartoffel", 0.25), new Artikel("Tomate", 0.25)};

Upvotes: 2

Gareth Davis
Gareth Davis

Reputation: 28059

An alternative using an Iterable instead of an Array:

Warenkorb(String kunde, Iterable<? extends Artikel> artikel){
    this.kunde = kunde;
    artikelliste = artikel;
    sessionid = s.nextInt();
    summe = 0;
    for(Artikel preis : artikel){
            summe += preis.verkaufspreis;
    }
}

Can still be constructed using the other array based syntax but also:

new Warenkorb("Buffy", Arrays.asList(new Artikel("foo",0.0), new Artikel("bar",1.0));

works with any implementation of Iterable such as ArrayList or HashSet etc

Upvotes: 1

matt b
matt b

Reputation: 139931

Is this what you want?

Artikel[] artikels = new Artikel[2];
artikels[0] = new Artikel("John Doe", 0);
artikels[1] = new Artikel("Jane Doe", 1);
Warenkorb w = new Warenkorb("something", artikels);

Your question isn't really clear on what you want to do...

Upvotes: 2

willcodejavaforfood
willcodejavaforfood

Reputation: 44063

new Warenkorb("Dieter", new Artikel[] {new Artikel("Kartoffel", 0.25))};

Is this what you are trying to do?

Upvotes: 3

Related Questions