1

I am trying to get input from a string containing ints. So when a user types in the command "getrange(1,12)" I need to read the inital command as a string, and the two numbers inside it as an ints. I was thinking I could do a number of Splits() but I think that might get messy. In addition Split() keeps them as strings I think.

My ultimate goal is to write an IF statement like this:

if("getrange")
{

    while(1 <= 12)
    {
        output.println(MyArray[1])
        1++
    }
}

Any Ideas? I know this is pretty crude, let me know if I need to clarify. Thanks

3 Answers 3

2
String input = "getrange(1,12)";
String[] parts = input.split("\\(");
System.out.println("Command: " + parts[0]);
String[] argsParts = parts[1].substring(0, parts[1].indexOf(")")).split(",");
int arg1 = Integer.parseInt(argsParts[0].trim());
int arg2 = Integer.parseInt(argsParts[1].trim());        
System.out.println("Args: " + arg1 + ", " + arg2);

Output:

Command: getrange
Args: 1, 12
Sign up to request clarification or add additional context in comments.

Comments

2
 Scanner s = new Scanner(input);
 s.findInLine("getRange\((\\d+),(\\d+)\)");
 MatchResult result = s.match();
 //You should do some error checking here (are there enough matches ...)
 int StartRange == Integer.parseInt(result.group(0));
 int EndRange == Integer.parseInt(result.group(1));

And you can take it from there :)

Comments

1

Use a regular expression to get the numbers and then then do an Integer.parseInt() on the two pieces. The other option which is less ideal would be to do a combo of substring and split to remove the unwanted characters.

Comments

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.