I’m trying to get a random string from a list of quotes defined inside of an OpenHAB rule, and having difficulty understanding how to do it. I’ve tried a variety of seemingly standard java ways to do this, but to no avail; must be missing something. For instance, lets say we’re working with the following rule:
rule "VoiceCMD"
when
Item VoiceCMD received update
then
var String voicecmd = VoiceCMD.state.toString.toLowerCase
if (voicecmd.contains('say a quote')) {
var Quotes = newArrayList(
"Power to four-hundred percent capacity.",
"You are malfunctioning.",
"You are in distress.",
"I believe your intentions to be hostile.",
"Sir, I think I need to sleep now..."
)
Random r = new Random()
var msg = r.nextInt(Quotes.length)
sendCommand(VoiceCMD_Response, msg)
}
end
In this example, ‘Random r’ throws errors in OpenHAB Designer and everything below it does not work. How can we access a random string value from the list, to set ‘var msg’ before calling the SendCommand()?
@samverner777 - thanks for that! I had already included the global ‘import java.util.Random’, and had also briefly looked at the ‘val’ approach. This (linked) approach seemingly works for random integers but I’m still at a loss to get this working for random strings from a list. (also attempted this further per your suggestion!) Guessing I need to use the int to select the list value by key/id, but don’t understand the DSL syntax well enough, yet
Correct. Create an ArrayList with your Strings, or a HashMap, though an ArrayList is probably more appropriate.
Use the random number generator to create a number between 0 and the number of items in your list. Then call myList.get(rndm) where myList is the list with Strings in it and rndm is your randomly generated Int.
Thanks all for the help. Here is my working solution for getting a random string from the Array!
val java.util.Random rand = new java.util.Random
rule "VoiceCMD"
when
Item VoiceCMD received update
then
var String voicecmd = VoiceCMD.state.toString.toLowerCase
if (voicecmd.contains('say a quote')) {
var Quotes = newArrayList(
"Power to four-hundred percent capacity.",
"You are malfunctioning.",
"You are in distress.",
"I believe your intentions to be hostile.",
"Sir, I think I need to sleep now..."
)
var i = rand.nextInt(5);
var msg = Quotes.get(i)
sendCommand(VoiceCMD_Response, msg)
}
end