tags:

views:

133

answers:

4

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?

+3  A: 
new Warenkorb("Dieter", new Artikel[] {new Artikel("Kartoffel", 0.25))};

Is this what you are trying to do?

willcodejavaforfood
mmmm... Kartoffel... food is the only way I'm going to remember any of my Deutsch.
Jason S
I hope I spelled that right :)
willcodejavaforfood
Your spelling is great ;).I am dying of jealousy, i also want to be a java guru...
mrt181
+2  A: 

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...

matt b
well we covered 2 possibilities :)
willcodejavaforfood
+1. Exactly, you're like Tweedle-Dee and Tweedle-Dum. (and I meant that in the best possible way :)
Jason S
at least his names were more locale-appropriate...
matt b
yeah, what are the German equivalents for Jane Doe and John Doe?
Jason S
They are Max Mustermann and Erika Mustermann
mrt181
+1  A: 

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

Gareth Davis
+2  A: 

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)};
Andreas_D
Yep, varargs are the way to go here. +1
Michael Myers