This is my class:
class StockQuote {
Float[] high, low, close, open;
public float GetMax(String choose_data_type) {
if data_type="high" {
Routine_Searchmax(high)
} elseif strdata_type="low" {
Routine_Searchmax(low)
}
}
private float Routine_Searchmax(float[] variable) {
// here i search max value into my array
}
}
My Question is: it is possible to pass a string variable with the name of a variable array, then .. work on that specific variable ? Is there a way to do that ? Thanks
Implement one single private method that take the name of the variable as parameter and return the corresponding float array. Then you can use this helper method in all the methods that implement you calculation.
If your parameter to identify the variable is an string, then the easyest way to "transform" it to the float array is an kind if-cascade.
if(name.equals("high") return this.high;
if(name.equals("low")...
throw new IllegalArgumentExeption();
If you have many of this Variables (high, low, ...) then you may should use reflection instead of this if-cascade.
An impovent would be to use an ENUM instead of the string!
But im my oppinion a much better solution would be using object orientation! Make high, low, ... instances of an class that implements getMax only for its own valus. So you can do this:
MyClass high = new MyClass;
...
float higgMax = high.getMax();
A better way is to do it by using enum
Enum Declaration
public enum Float
{
HIGHT("high"), LOW("low"), CLOSE("close"), OPEN("open");
String code;
Float(String code)
{
this.code=code;
}
// add getter and setter for string code here
}
Class Dec
public class StockQuote {
public Float getMax(String chooseDataType) {
return routineSearchmax (Float.valueOf(chooseDataType));
}
//This float is now enum
private Float routineSearchmax(Float variable) {
// here i search max value into my array
}
}
But like these guys are saying you could just do it with out it as well but neater this way in my opinion also notice no if statement.
精彩评论