0

The code below has a run method which takes in a columnNumber. I have 3 different arrays: col1, col2, and col3 initialized at the top with 4 elements in each of them.

Let's say in the run method, I pass in an int value of 2. So, I would like "s[0] = 500" to be "col2[0] = 500".

So, is there a way to specify which int array that I want by passing in an integer value?

e.g., I type in 3 and then "s[0] = 500" will be "col3[0] = 500"

public class Array {

static int[] col1 = {1, 2, 3, 4};  
static int[] col2 = {1, 2, 3, 4};
static int[] col3 = {1, 2, 3, 4};


public static void run(int columnNumber) {



    String string = Integer.toString(columnNumber);

    String s = "col" + string;

    s[0] = 500;
1
  • The run() method should take an int[] array as argument, instead of a column number. And you would thus pass it the array you want the method to modify. Commented Nov 15, 2014 at 16:51

3 Answers 3

2

You can't (easily) refer to variable names dynamically. What you probably want here is an array of arrays:

static int[][] cols = {
    {1, 2, 3, 4},
    {1, 2, 3, 4},
    {1, 2, 3, 4}
};

public static void run(int columnNumber) {
    cols[columnNumber - 1][0] = 500;
}

I've used columnNumber - 1 because array indices are 0-based. So if you call run(1) it will modify the first array in cols (cols[0]).

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

Comments

0

I suggest that you can use a switch statement.

switch(columnNumber){
      case 1:
          col1[0]=500;
          break;
      case 2:
          col2[0]=500 ;
          break;
      case 3:
          col3[0]=500; 
          break;  
}

Comments

0

What about this?

static int[][] columns = { 
                        { 1, 2, 3, 4 },
                        { 1, 2, 3, 4 },
                        { 1, 2, 3, 4 }, 
                        { 1, 2, 3, 4 } 
                        };

public static void run(int columnNumber) {

    columns[columnNumber][0] = 500;

}

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.