In a Groovy Program How Do You Assign an Element in an Index to Be the Value of a Given Variable?

Problem scenario
You are trying to write a simple Groovy program.  You have an array of individual strings.  How do you assign one of them to be the value that a variable is?

Solution
To assign an element of an array, should have quotes around the variable and the $ symbol and the syntax " as String" should follow the closing quote mark.

def input = System.console().readLine 'Please provide some input: '
def x = input
def boardArray = new String[2]
boardArray[0] = ""
boardArray[1] = ""
boardArray[1] = "$x" as String   //This is the correct version
println boardArray[1]

Leave a comment

Your email address will not be published.