so i have the following task:
Given is the following class:
public class Konto {
private final String inhaber;
private double guthaben;
public Konto(String inhaber) {
this.inhaber = inhaber;
}
public String getInhaber() {
return inhaber;
}
public double getGuthaben() {
return guthaben;
}
public void einzahlen(double betrag) {
guthaben += betrag;
}
public void auszahlen(double betrag) {
guthaben -= betrag;
}
}
Using these classes, implement another class named Bank with the following properties:
The attribute named accounts is a directory of all
Account numbers and related accounts
(java.util.HashMap) and should be initialized in a default constructor of the class.
Write the addKonto method to add a new account of type Account, a getKonto method to query an account by its number, and a method called removeKonto that deletes an account with a specific number.
Implement a getGesamtguthaben method that returns the sum of the Balance(guthaben) of all bank accounts.
Write a containsKonto method that checks if an account with the given number exists in the bank and returns a corresponding Boolean value.
this is my code:
package Bank;
import java.util.HashMap;
import java.util.Map;
public class Bank {
private Map<String, Konto> konten;
public Bank() {
konten = new HashMap<String, Konto>();
}
public Konto addKonto(Konto konto) {
return konten.put(konto.getInhaber(), konto);
}
public String getKonto(String kontonr) {
if(konten.containsKey(kontonr)) {
return kontonr;
}
return null;
}
public Konto removeKonto(String kontonr) {
return konten.remove(kontonr);
}
public double getGesamtguthaben() {
for(double guthaben : konten) {
}
}
public boolean containsKonto(String kontonr) {
if(konten.containsKey(kontonr)) {
return true;
}else {
return false;
}
}
}
SO my question is how do i sum the balance of all Bank Accounts with a own method? And are the other methods correct? all help is appreciated
Use Map.entrySet to iterate over the entries.
double sum = 0;
for (Map.Entry<String, Konto> entrySet : konten.entrySet()) {
sum += entrySet.getValue().getGuthaben();
}
return sum;
Or using streams and Collectors.summarizingDouble
double sum = konten.entrySet()
.stream()
.collect(Collectors.summarizingDouble(entry -> entry.getValue().getGuthaben()))
.getSum();
Yes like user7 said. But instead of using the entrySet() you could also use the values() method.
double sum = konten.values()
.stream()
.collect(Collectors.summarizingDouble(konto-> konto.getGuthaben()))
.getSum();
Related
I created an item named player as follows:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
public class player implements Comparable <player> {
int PlayerId ;
String name ;
double salary;
public player(int PlayerId) {
this.PlayerId = PlayerId;
}
public void setPlayerId(int PlayerId) {
this.PlayerId = PlayerId;
}
public void setName(String name) {
this.name = name;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getID() {
return PlayerId;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
#Override
public int hashCode() {
int key = 2;
return key=2*key+PlayerId;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final player other = (player) obj;
if (this.PlayerId != other.PlayerId) {
return false;
}
return true;
}
#Override
public String toString(){
return hashCode()+" "+getID() +" "+getName()+" "+getSalary();
}
// generic method StoreplayerDetails
public <T> void StoreplayerDetails( HashMap<Integer,T> inputMap ) {
// save elements into text file
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream("OutPut.txt"));
for(T element : inputMap.values())
pw.println(element);
pw.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(MainProgram.class.getName()).log(Level.SEVERE, null, ex);
} finally {
pw.close();
}
}
#Override
public int compareTo(player other) {
if(this.salary>other.salary)
return 1;
else
if(this.salary<other.salary)
return -1;
return 0;
}
public interface Update {
public <T> void updateSalaries( HashMap<Integer,player> inputMap);
}
}
create an interface named update in the player class ,create a generic method named updateSalaries in the interface that takes a HashMap as input and returns a Queue of player objects after updating the salaries of players by adding 500 to each one's salary .
in the mainprogram class implement the method updatesalaries as a lamdba expression .in the mainprogram class,print the elements in the returned queue .
I tried it as follows but it did not work out:
#Override
public <T> void updateSalaries(HashMap<Integer, player> map) {
map.replaceAll((k,player.getSalary()) -> player.getSalary()+500;
System.out.println("new map"+map);
}
This is the full code in the main class
import java.util.HashMap;
import player.player.Update;
public class MainProgram implements Update{
public static void main(String[] args) {
HashMap< Integer,player> Keys = new HashMap<>();
player p1 =new player(1);
p1.setName("Ali");
p1.setSalary(5000);
player p2 =new player(2);
p2.setName("Sayed");
p2.setSalary(7000);
player p3 =new player(3);
p3.setName("soha");
p3.setSalary(3000);
Keys.put(1, p1);
Keys.put(2, p2);
Keys.put(3, p3);
// p1.StoreplayerDetails(Keys);
MainProgram m = new MainProgram();
m.updateSalaries(Keys);
}
#Override
public <T> void updateSalaries(HashMap<Integer, player> map) {
map.replaceAll((k,player.getSalary()) -> player.getSalary()+500;
System.out.println("new map"+map);
}
}
Is there any help in solving this?
In your code snippet you have the following line of code:
map.replaceAll((k,player.getSalary()) -> player.getSalary()+500;
Let's take this apart piece by piece:
map.replaceAll This method lets you replace all the values in a map. I believe you want to manipulate the values that are already there, instead.
(k,player.getSalary()) This is where you name the variables that the lambda will dump values into. You aren't supposed to supply numbers here, you are supposed to be receiving numbers. You likely want (k, p), where k will be set to the key (an Integer) and p will be set to the value (a player).
player.getSalary()+500 This returns an int. The replaceAll method requires that you return the value type, which in this case is player.
You forgot to include a close parenthesis at the end.
I believe you want to use this line of code instead, which mitigates all of the above errors:
map.forEach((k, p) -> p.setSalary(p.getSalary() + 500));
I have a series of small arrays (consisting of two doubles), many of which are
the same. E.g.
{5.0, 15.0}
{5.0, 15.0}
{5.0, 15.0}
{12.0, 8.0}
{10.0, 8.0}
{10.0, 8.0}
I want to be able to count the number of each arrays, i.e.
3 of {5.0, 15.0}
1 of {12.0, 8.0}
2 of {10.0, 8.0}
To do this, I tried making use of a LinkedHashMap (linked, because the order
might come into use later on):
import java.util.Map;
import java.util.LinkedHashMap;
public class MapArrayInt {
Map<double[], Integer> arrays = new LinkedHashMap<double[], Integer>();
public static void main(String[] args) {
MapArrayInt mapArrayInt = new MapArrayInt();
mapArrayInt.addArray(5.0, 15.0);
mapArrayInt.addArray(5.0, 15.0);
mapArrayInt.addArray(5.0, 15.0);
mapArrayInt.addArray(12.0, 8.0);
mapArrayInt.addArray(10.0, 8.0);
mapArrayInt.addArray(10.0, 8.0);
System.out.println(String.valueOf(mapArrayInt.arrays.get(new double[]{5.0, 15.0})));
System.out.println(String.valueOf(mapArrayInt.arrays.get(new double[]{12.0, 8.0})));
System.out.println(String.valueOf(mapArrayInt.arrays.get(new double[]{10.0, 8.0})));
}
void addArray(double val1, double val2) {
double[] newArray = new double[]{val1, val2};
if (!arrays.containsKey(newArray)) {
arrays.put(newArray, 1);
} else {
arrays.put(newArray, arrays.get(newArray) + 1);
}
}
}
I expected this output,
3
1
2
but got,
null
null
null
I'm quite new to Java, but I suspect this might be because each double[] counts as a unique because they are different instances, even though they contain the same two doubles.
How can I fix this, if I should at all (is there a better way)? I just need a data structure that allows me to
Add doubles[]
Preserves order of doubles[]
Easily iterate through to get doubles[] and number of said doubles[]
As I stated in my comment, with new you're creating a new instance of an object. Which means that the arrays you added with mapArrayInt.addArray(5.0, 15.0); and the arrays in mapArrayInt.arrays.get(new double[]{5.0, 15.0}) reference different objects. That's why you get null, because for the map those are different keys.
In order to circumvent this, you could create a custom wrapper class
import java.util.Arrays;
public class Exercise {
private final double[] array;
public Exercise(double first, double second) {
this.array = new double[]{first, second};
}
public boolean equals(Object obj) {
if(!(obj instanceof Exercise)) {
return false;
}
Exercise other = (Exercise)obj;
return Arrays.equals(this.array, other.array);
}
public int hashCode() {
return Arrays.hashCode(array);
}
}
The equals and hashCode methods are important, when you want to use this class in collections like Map, otherwise the hashcode of Object is used for checking equality and you'd have the same problem as you have now.
Then, in your main class you can use it like so:
void addArray(double val1, double val2) {
Exercise exercise = new Exercise(val1, val2);
if (!arrays.containsKey(exercise)) {
arrays.put(exercise, 1);
} else {
arrays.put(exercise, arrays.get(exercise) + 1);
}
}
And System.out.println(String.valueOf(mapArrayInt.arrays.get(new Exercise(5.0, 15.0))));
EDIT:
I changed one of the doubles to int (you said you're representing reps and weight ... and reps can only be a natural number right?)
You could build create an Exercise-Class like below and use the static method "of" to create the instances:
package somepackage;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
public class Exercise
{
private static final Map<Integer, Map<Double, WeakReference<Exercise>>> instances = new HashMap<>();
private final int reps;
private final double weight;
private Exercise(int reps, double weight)
{
this.reps = reps;
this.weight = weight;
}
public static Exercise of(int reps, double weight)
{
if (!instances.containsKey(reps))
{
instances.put(reps, new HashMap<>());
}
Map<Double, WeakReference<Exercise>> innerMap = instances.get(reps);
WeakReference<Exercise> weakRef = innerMap.get(weight);
Exercise instance = null;
if (weakRef != null)
{
instance = weakRef.get();
}
if (weakRef == null || instance == null || weakRef.isEnqueued())
{
instance = new Exercise(reps, weight);
innerMap.put(weight, new WeakReference<>(instance));
}
return instance;
}
public int getReps()
{
return this.reps;
}
public double getWeight()
{
return this.weight;
}
}
And then you could put those exercises in a map like below:
public void addArray(int reps, double weight)
{
Exercise exercise = Exercise.of(reps, weight);
if (!arrays.containsKey(exercise))
{
arrays.put(exercise, 1);
}
else
{
arrays.put(exercise, arrays.get(exercise) + 1);
}
}
OR:
Instead of an double[] as key you can use the a Map<Double, Integer> as your value for 2 values:
package somepackage;
import java.util.HashMap;
import java.util.Map;
public class MapArrayInt
{
private final Map<Double, Map<Double, Integer>> values;
public MapArrayInt()
{
this.values = new HashMap<>();
}
public void addArray(double val1, double val2)
{
if (!this.values.containsKey(val1))
{
this.values.put(val1, new HashMap<>());
}
Map<Double, Integer> innerValues = this.values.get(val1);
if (innerValues.containsKey(val2))
{
innerValues.put(val2, innerValues.get(val2) + 1);
}
else
{
innerValues.put(val2, 1);
}
}
public int getArrayValue(double val1, double val2)
{
Map<Double, Integer> innerValues = this.values.get(val1);
if (innerValues == null)
{
// you may also throw an Exception here
return 0;
}
Integer value = innerValues.get(val2);
if (value == null)
{
// also here you may throw an Exception
return 0;
}
return value;
}
public int getArrayValue(double[] values)
{
return getArrayValue(values[0], values[1]);
}
}
So I'm taking a basic course in Java at university. I'm trying to create a class Bachelorstudents containing an arraylist of class Bachelorstudent (respectively plural and singular of "bachelorstudents" in english) which contains a HashMap of course (key) and marks (value).
My problem is the infamous "non-static method cannot be referenced from a static context".
"Bachelorstudent"-class:
public class Bachelorstudent{
private String navn;
private int studentNummer;
private HashMap<String, Integer> karakterListe = new HashMap<>();
public Bachelorstudent(String navn, Integer studentNummer){
setNavn(navn);
setStudentNummer(studentNummer);
}
public Bachelorstudent(){
}
public void setKarakter(String fagkode, Integer karakter){
karakterListe.put(fagkode, karakter);
}
public HashMap<String, Integer> getKarakter(){
return karakterListe;
}
public int snitt(){
Integer snittKarakter = 0;
int counter = 0;
if(!karakterListe.isEmpty()){
for(Integer karakter : karakterListe.values()){
snittKarakter += karakter;
counter++;
}
}else{
return 6;
}
return snittKarakter /= counter;
}
public int getKarakterer(){
Integer karakterer = 0;
if(!karakterListe.isEmpty()){
for(Integer karakter : karakterListe.values()){
karakterer += karakter;
}
}else{
return 0;
}
return karakterer;
}
public void setNavn(String navn){
this.navn=navn;
}
public String getNavn(){
return navn;
}
public void setStudentNummer(int studentNummber){
this.studentNummer=studentNummer;
}
public int getStudentNummer(){
return studentNummer;
}
}
"Bachelorstudenter"-class:
public class Bachelorstudenter{
private ArrayList<Bachelorstudent> bachelorStudenter = new ArrayList<>();
public Bachelorstudenter(){
}
public void karakterSnitt(){
for(Bachelorstudent bachelorstudenter : bachelorStudenter){
Bachelorstudent student = new Bachelorstudent();
for(Bachelorstudent bachelorstudent : Bachelorstudent.getKarakter()){ //<-- Non-static method error.
}
}
}
public Boolean eksisterer(Bachelorstudent student){
boolean finnes = false;
for(Bachelorstudent bachelorstudent : bachelorStudenter){
if(bachelorstudent.getNavn().equals(student.getNavn())){
finnes = true;
}
}
return finnes;
}
public Boolean nyBachelorstudent(Bachelorstudent student){
if(!eksisterer(student)){
bachelorStudenter.add(student);
return true;
}
else{
System.out.println("Eksisterer i systemet fra før");
return false;
}
}
}
I have tried several things, such as calling an instance of class Bachelorstudent (as seen above), tried inheritance (not sure if I did this right, but what I did didn't work). How can I call on the .getKarakter() method in class Bachelorstudenter?
Edit: Just to clarify. The point of this method is to get the average of every mark of every bachelorstudent. I have a method in Bachelorstudent which does this, but I need the equivalent in Bachelorstudenter, which will find the average of every mark of every course of every student.
You need to use an object to call a non-static method.
In your example, you need to use the object of the current iteration to invoke the method:
for(Bachelorstudent bachelorstudenter : bachelorStudenter){ // Iterate over the bachelorStudenter list.
bachelorstudenter.getKarakter(); // Use the bachelorstudenter of this iteration.
}
I have a class which extends number.
public class Quantity extends Number{
}
And the class as,
public class Test{
Quantity tkphMaxValue;
Quantity tkphValue;
public Test(Quantity tkphValue, Quantity maxValue){
this.tkphValue= tkphValue;
this.maxValue= maxValue;
}
public Quantity getTkphValue() {
return tkphValue;
}
public void setTkphValue(Quantity tkphValue) {
this.tkphValue = tkphValue;
}
public Quantity getTkphMaxValue() {
return tkphMaxValue;
}
public void setTkphMaxValue(Quantity maxValue) {
this.tkphMaxValue = maxValue;
}
}
I need to divide ((getTkphValue()/getTkphMaxValue())*100) to get the percentage value.
How can I convert the Quantity object to number?
Try this:
((getTkphValue().doubleValue()/getTkphMaxValue().doubleValue())*100)
Before you do, make sure that tkphMaxValue and tkphValue are not null.
I have a set of objects. This objects calculate some numbers based on request parameters. Let's call them calculators. Each calculator has description where specified type of requests that this calculator the most suitable for.
For example,
Calculator1 : with this parameters : price > 10, gender = male, geo_id = 1, 2 or 3.
Calculator2 : with this parameters : price < 5, gender = male, geo_id = 1, 2.
For request : price = 11, gender = male, geo_id = 2 I should get calculator1 like the most suitable and then calculator2.
For request : price = 4, gender = male, geo_id = 2 I should get calculator2 and then calculator1.
For request : price = 3, gender = female, geo_id = 5 I should get only the second one.
Now I'm doing it with Lucene, but it's not really fit for this task. Can you recommend me some library or approach?
My suggestion would be to use a comparator. See a sketch of the classes below.
import java.util.HashMap;
import java.util.Map;
public abstract class Calculator {
public static Map<String, Integer> weights;
static {
weights = new HashMap<String, Integer>();
weights.put("price", 10);
weights.put("gender", 2);
weights.put("geo", 5);
}
public abstract int calculate(Map<String, Integer> request);
public abstract int fitnessFor(Map<String, Integer> request);
}
You can use the weights to adjust relative importance of the individual request parameters.
import java.util.Map;
public class Calculator1 extends Calculator {
public int calculate(Map<String, Integer> request) {
return -1;
}
#Override
public int fitnessFor(Map<String, Integer> request) {
int fitness = -1;
Integer price = request.get("price");
if (price == null)
return fitness;
if (price > 10)
fitness += weights.get("price");
return fitness;
}
public String toString() { return "Calculator1"; }
}
Calculator1 cares only about the pricey items.
import java.util.Map;
public class Calculator2 extends Calculator {
public int calculate(Map<String, Integer> request) {
return -1;
}
#Override
public int fitnessFor(Map<String, Integer> request) {
int fitness = -1;
Integer price = request.get("price");
if (price == null)
return fitness;
if (price < 5)
fitness += weights.get("price");
Integer gender = request.get("gender");
if (gender == null)
return fitness;
if (gender == 1)
fitness += weights.get("gender");
return fitness;
}
public String toString() { return "Calculator2"; }
}
Calculator2 cares about the less pricey items esp. if they are for gender 1.
The comparator just compares Calculators by their fitness relative to the request:
import java.util.Comparator;
import java.util.Map;
public class CalcComparator implements Comparator<Calculator> {
private Map<String, Integer> request;
public CalcComparator(Map<String, Integer> request) {
this.request = request;
}
#Override
public int compare(Calculator c1, Calculator c2) {
int c1Fitness = c1.fitnessFor(request);
int c2Fitness = c2.fitnessFor(request);
if (c1Fitness == c2Fitness)
return 0;
if (c1Fitness < c2Fitness)
return 1;
return -1;
}
}
Try it out with:
public class Main {
public static void main(String[] args) {
Map<String, Integer> request = new HashMap<String, Integer>();
request.put("price", 5);
request.put("gender", 1);
List<Calculator> calculators = new ArrayList<Calculator>();
calculators.add(new Calculator1());
calculators.add(new Calculator2());
Collections.sort(calculators, new CalcComparator(request));
System.out.println("For request: "+request);
for (Calculator c : calculators) {
System.out.println("\t"+c.toString() + "( fitness " + c.fitnessFor(request) + ")");
}
}
}
This is just a sketch to illustrate the idea. You will probably want to introduce an enum for the request parameters, maybe introduce a Request class, most likely change completely how fitness is computed, make some of the fields private and encapsulate them, etc.
The advantage is that you easily get an ordering of all the Calculators based on their fitness for the request.
Provided that I understood you correctly, I would suggest that you use the Specification design pattern which is used in cases like this. There's no need in such a fancy library like Lucene for such a simple task. The advantage of the Specification pattern is that it keeps all the filtering logic grouped and encapsulated. Your implementation may vary, but below is a simple example of what it could look like
public interface Specification<T> {
boolean isSatisfiedBy(T candidate);
Specification<T> and(Specification<T> specification);
Specification<T> or(Specification<T> specification);
Specification<T> not(Specification<T> specification);
}
public abstract class Calculator {
// ...
}
public class Calculator1 extends Calculator implements Specification<Request> {
public boolean isSatisfiedBy(Request request) {
// check if the request fits this calculator
}
}
public class Calculator2 extends Calculator implements Specification<Request> {
public boolean isSatisfiedBy(Request request) {
// check if the request fits this calculator
}
}
You can then have a collection or a pool of calculators such that
public class Calculators {
private final List<RequestSpecification> calculators;
public Calculator getOneSuitedFor(Request request) {
for (Calculator calculator : calculators) {
if (calculator.isSatisfiedBy(request)) {
return calculator;
}
}
return null;
}
}
And here how you would use it
Calculator calculator = Calculators.getOneSuitedFor(request);
Or, if needed, you can always go on and expand on it by making use of composition (see the reference link above) which allows for logic chaining and combining of different specifications depending on the context. This, however, would require a little bit different class design from that of above, but is more flexible
final Request request;
Specification<Calculator> price = new Specification<>() {
public boolean isSatisfiedBy(Calculator calculator) {
return calculator.supportsPrice(request.getPrice());
}
};
Specification<Calculator> gender = new Specification<>() {
public boolean isSatisfiedBy(Calculator calculator) {
return calculator.supportsGender(request.getGender());
}
};
Specification<Calculator> region = new Specification<>() {
public boolean isSatisfiedBy(Calculator calculator) {
return calculator.supportsRegion(request.getRegion());
}
};
Specification calcSpec = price.and(gender).and(region);
boolean isSatisfied = calcSpec.isSatisfiedBy(calculator);
Another interesting example is to use named specifications
Specification<Calculator> teenager = new Specification<>() {
public boolean isSatisfiedBy(Calculator calculator) {
return calculator.getAge() >= 13 && calculator.getAge() <= 19;
}
};
Specification<Calculator> male = new Specification<>() {
public boolean isSatisfiedBy(Calculator calculator) {
return calculator.getGender().equals("male");
}
};
Specification<Calculator> fromEurope = new Specification<>() {
public boolean isSatisfiedBy(Calculator calculator) {
return calculator.getRegion().equals("Europe");
}
};
Specification<Calculator> calcSpec = teenager.and(male).and(fromEurope);
boolean isSatisfied = calcSpec.isSatisfiedBy(calculator);
You could maybe try something like this:
public enum Calculator
{
CALC1
{
#Override
protected int matchCount( Map parameters )
{
// TODO count how many conditions match
return 0;
}
#Override
protected int calc( Map parameters )
{
// TODO
return 0;
}
},
CALC2
{
#Override
protected int matchCount( Map parameters )
{
// TODO count how many conditions match
return 0;
}
#Override
protected int calc( Map parameters )
{
// TODO
return 0;
}
};
protected abstract int matchCount( Map parameters );
protected abstract int calc( Map parameters );
public int doCalc( Map parameters )
{
Calculator mostSuited = null;
int maxCount = 0;
for ( Calculator calc : values() )
{
int matchCount = calc.matchCount( parameters );
if ( matchCount > maxCount )
{
mostSuited = calc;
}
}
return mostSuited.calc( parameters );
}
}
The way you would use the above is by invoking: int result = Calculator.doCalc( parameters )
Create a Calculator base class :
public static abstract class Calculator {
// This Contains the common score calculation methods.
public int getScore(int price, String gender, int geo_id) {
int score = 0;
if (gender.equalsIgnoreCase("male"))
score++;
if (getGeoIds().contains(geo_id))
score++;
return score;
}
public ArrayList<Integer> getGeoIds() {
// Fetching the common list of geo points to be compared.
ArrayList<Integer> lst = new ArrayList<Integer>();
lst.add(1);
lst.add(2);
return lst;
}
public abstract void doCalculation();
}
Then create your calculator classes by extending from this base.
public static class Calcualtor1 extends Calculator {
#Override
public int getScore(int price, String gender, int geo_id) {
// fetching score from common score calculation.
int score = super.getScore(price, gender, geo_id);
// Adding its own score logic.
if (price > 10)
score++;
return score;
}
#Override
public void doCalculation() {
// Do your actual work.
}
#Override
public ArrayList<Integer> getGeoIds() {
ArrayList<Integer> lst = super.getGeoIds();
// Adding the geo id to compare for this calculator.
lst.add(3);
return lst;
}
}
public static class Calcualtor2 extends Calculator {
#Override
public int getScore(int price, String gender, int geo_id) {
// fetching score from common score calculation.
int score = super.getScore(price, gender, geo_id);
// Adding its own score logic.
if (price < 5)
score++;
return score;
}
#Override
public void doCalculation() {
// Do your actual work.
}
}
Initialise values :
//To store the list of available calculators.
private static ArrayList<Class<? extends Calculator>> calculators;
static {
//Initializing the calculator list in static constructor.
calculators = new ArrayList<Class<? extends Calculator>>();
calculators.add(Calcualtor1.class);
calculators.add(Calcualtor2.class);
}
Actual processing :
public static void main(String[] args) {
int price = 10;
String gender = "male";
int geo_id = 2;
Calculator calculator = null;
int score = 0;
for (Class<? extends Calculator> calClass : calculators) {
Calculator cal = null;
try {
cal = calClass.newInstance();
} catch (Exception e) {
continue;
}
int calScore = cal.getScore(price, gender, geo_id);
if (calScore > score) {
calculator = cal;
score = calScore;
}
}
if (calculator != null) {
calculator.doCalculation();
}
}