0

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?

4 Answers 4

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

Is this what you are trying to do?

Sign up to request clarification or add additional context in comments.

2 Comments

mmmm... Kartoffel... food is the only way I'm going to remember any of my Deutsch.
Your spelling is great ;). I am dying of jealousy, i also want to be a java guru...
2

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

3 Comments

well we covered 2 possibilities :)
+1. Exactly, you're like Tweedle-Dee and Tweedle-Dum. (and I meant that in the best possible way :)
yeah, what are the German equivalents for Jane Doe and John Doe?
2

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)};

1 Comment

Yep, varargs are the way to go here. +1
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.