Reputation: 249
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
Upvotes: 1
Views: 134
Reputation: 51030
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
Upvotes: 2
Reputation: 16576
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 :)
Upvotes: 2
Reputation: 2644
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.
Upvotes: 1