I have two classes, one for articles and another for the cart. The cart consists of an object-array, which contains article objects.
I need to sum up the prices of the articles with a foreach-loop within the constructor. When I write the method (that is probably wrong) within the constructor than its type is not accepted as double. How can I sum up fields of objects within an object-array and how do I do this inside a constructor (<- this looks like a bad design decision, but it is part of may class work).
Here are my classes:
package org.teubler.sucks.aufgaben;
public class Artikel {
public enum Warengruppe{
A, B, C, S
}
String name;
double verkaufspreis;
Warengruppe Art;
Artikel(String name, double preis){
this.name = name;
this.verkaufspreis = preis;
this.Art = Warengruppe.S;
}
public double getVerkaufspreis() {
return verkaufspreis;
}
public void setWarengruppe(Warengruppe Art) {
switch(Art){
case A:Art = Warengruppe.A;
case B:Art = Warengruppe.B;
case C:Art = Warengruppe.C;
default: Art = Warengruppe.S;
}
}
}
second class
package org.teubler.sucks.aufgaben;
import java.util.Random;
public class Warenkorb {
String kunde;
Artikel artikelliste[];
int sessionid;
Random s = new Random();
Warenkorb(String kunde, Artikel[] artikel){
this.kunde = kunde;
this.artikelliste = artikel;
this.sessionid = s.nextInt();
public double gesamtpreis(){
double summe = 0;
for(Artikel preis : artikel){
summe += artikel.getVerkaufspreis();
}
return summe;
}
}
}
You’re trying to create an extra method within the constructor. That’s not a good idea. You’re also trying to index an array by an object, which won’t work. Finally, you’re trying to call
getVerkaufspreis()on anObject, instead of a strongly-typedArtikel. Try this:Now by the end of the loop you’ll have the sum – but what do you want to do with it? I suspect you want to create a field for it…
If you absolutely have to use an
Object[]instead of anArtikel[]then you should cast on each iteration: