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?
new Warenkorb("Dieter", new Artikel[] {new Artikel("Kartoffel", 0.25))};
这是您要做什么?
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...
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)};
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.