質問

I'm stuck at a point that seems simple and likely there's an easy way to deal with it, but I need help anyway.

I need to evaluate a formula using a set of constants, that should be chosen dynamically depending on the selection of the user. See the code:

double constOne=2.3, constTwo=1.1, constThree=1.7...; //and so on

public double doSomething(int inputOne, String selection){

    //being const... one of the double vars defined above, 
    //selected based on the String selection
    return inputOne*const...; 
}

I know I can do this using an array of doubles and passing to doSomething() the position on the array, but that's very hardcoded and really I prefer not to do it that way.

Is there a way to reference to the constOne, constTwo, etc. dynamically? Thanks!

PS: yes, I know could be a silly question, I'm learning!

役に立ちましたか?

解決

I don't really see the problem of declaring the constants in an array.

However if you are really against that you can write a helper function which will take in the selector String and return the constant. This could make your code cleaner

double getConstant(String selector) {
    // some logic
}

Then your other function would be a bit cleaner

public double doSomething(int inputOne, String selection){

    //being const... one of the double vars defined above, 
    //selected based on the String selection
    return inputOne * getConstant(selection); 
}

The benefit of doing it this way would be your logic for selecting a constant from a selector would be in one place rather than in all functions where you need the constants.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top