2

In short, the user will input a number (say 1 through 3). This will decide which range of numbers the loop should search through.

switch(input){
case 1:
    searchTerm = "i<10 && i>5";
case 2:
    searchTerm = "i>=10 && i<19";
case 3:
    searchTerm = "i>19 && i<24";
}
while(searchTerm){
    //some function
}


Is this possible? I I've not been able to find a way to use a string as search parameters.

EDIT: I don't think I did a very good job of explaining why I needed this. What is one to do if there are different numbers of parameters? For example:

case 1:
    searchTerm = "i<5"
case 2:
    searchTerm = "i>25 && i<29"
case 3:
    searchTerm = "(i<50 && i>25) && (i>55 && i<75)"
case 4:
    searchTerm = "(i<20 && i>15) && (i>300 && i<325) && (i>360 && i<380)

Then how does one do it? Multiple loops that call the same function?

5
  • 5
    Why would you want to use a string for this? Use numeric variables! Commented Aug 5, 2015 at 7:48
  • No, this is not possible, not necessary and a hell to maintain and debug. You define an expression in your string, which will have to be compiled to be used. Commented Aug 5, 2015 at 7:51
  • you can use i=6;eval(searchTerm = "i<10 && i>5";) in loop Commented Aug 5, 2015 at 7:54
  • @raghavendra: Java != JavaScript Commented Aug 5, 2015 at 7:56
  • @T.J.Crowder thank you sorry i too missed the tag Commented Aug 5, 2015 at 8:05

4 Answers 4

9

The correct way to do this is to not use a string at all:

int min, max;

switch(input){
case 1:      // i<10 && i>5
    min = 6;
    max = 10;
    break; // to avoid follow-through to the next case
case 2:     // i>=10 && i<19
    min = 10;
    max = 20;
    break;
case 3:     // i>19 && i<24
    min = 20;
    max = 25;
    break;
default:
    // You need something here in case the value entered wasn't 1-3
}
for (int i = min; i < max; ++i) {
    // ...
}

Re your edit:

I don't think I did a very good job of explaining why I needed this. What is one to do if there are different numbers of parameters?

In that case, you'll have to use an expression evaluator (or write one, which is a non-trivial task). There's one in Spring, for instance (not recommending, just happened to hear about it). A search for "Java expression evaluator" should turn up some options.

Another alternative, which is somewhat amusing given that some folks mistook your question for a JavaScript question, is to use the JavaScript evaluator built into Java (either Rhino or Nashorn). E.g.: Live Example

import javax.script.*;

class Ideone {
    public static void main(String[] args) throws java.lang.Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        String searchTerm = "i >= 19 && i <= 24";
        int i;
        try {
            i = 19;
            engine.put("i", i);
            while ((boolean)engine.eval(searchTerm)) {
                System.out.println("i = " + i);
                ++i;
                engine.put("i", i);
            }
            System.out.println("Done");
        } catch (ScriptException scriptException) {
            System.out.println("Failed with script error");
        }
    }
}

...but you'll still have the problem of determining what initial value to use for i, which I've hardcoded above.

Sign up to request clarification or add additional context in comments.

4 Comments

@Bathsheba: Thanks, yes, I meant to flag that up and forgot. :-)
I didn't use correct examples, but your answer definitely answered the question that was asked. What about the new question?
@Jimpy: I've added to the answer to address the updated question.
Thank you very much for your help! Your answer was extremely thorough and gives me lots of different angles to approach this problem on. It looks like I have a whole new task to tackle. Thank you again.
5

In Java 8 you can select a lambda instead of String:

Predicate<Integer> searchTerm = (Integer v) -> false;

switch (input) {
  case 1:
    searchTerm = (Integer v) -> v < 10 && v > 5;

    break;
  case 2:
    searchTerm = (Integer v) -> v >= 10 && v < 19;

    break;
  case 3:
    searchTerm = (Integer v) -> v > 19 && v < 24;

    break;
}

while (searchTerm.test(i)) {
  ...
}

1 Comment

Sadly thanks to the edit this no longer answers the question.
0

You can create an enumeration as below.

public enum SearchTerms {

    None(""),
    Between6And9("i<10 && i>5"),
    Between10And18("i>=10 && i<19"),
    Between20And23("i>19 && i<24");

    private final String stringValue;

    SearchTerms(String stringValue) {
        this.stringValue = stringValue;
    }

    public String getStringValue() {
        return stringValue;
    }

    public static SearchTerms fromStringValue(String stringValue) {
        for (SearchTerms searchTerm : values()) {
            if (searchTerm.getStringValue().equalsIgnoreCase(stringValue)) {
                return searchTerm;
            }
        }
        return SearchTerms.None;
    }

}

Usage:

SearchTerms searchTerm = SearchTerms.fromStringValue("i<10 && i>5");

switch(searchTerm) {
    case Between6And9:
        //dosomething
        break;
}

Comments

-5

You can use .eval() of JavaScript.

Also don't forget break; at the end of each case:

Check out this fiddle.

Here is the snippet.

function test(input, i) {
  switch (input) { //input=1
    case 1:
      searchTerm = "i<10 && i>5";       //this will be 'searchTerm'
      break;
    case 2:
      searchTerm = "i>=10 && i<19";
      break;
    case 3:
      searchTerm = "i>19 && i<24";
      break;
  }
  while (eval(searchTerm)) {      //'searchTerm' converted to boolean expression
    alert(i);           // alert for i=7,8,9
    i++;
  }
}

test(1, 7);           //pass input=1 and i=7

8 Comments

can be used but not a good one to use. recommend the down answer
He could, yes, if A) This were JavaScript instead of Java (they're completely different languages and environments), and B) He wanted to completely unnecessarily use a full JavaScript parser where simple variables were all that was needed.
meaningful to op question why down voting
@raghavendra: The wrong language is useful how, exactly? Shall we also post Fortran and Pascal answers? Perhaps some assembly code?
Sorry guys. My mistake. I didn't see the tag. Just saw the code. I took it to be javascript. I will delete this answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.