Conditional inside an IF

is there a way to put a conditional inside an of stament? for

for (int i=0; i<10; i++){
  if(i==col(i).size ){//col1 or col2... col 9 depending on the i

    //whatever you want

what i am currently using is this a separate void that gets the size in a global variable and then use that variable.

i use a void because is a preces that i repet a lot. but i would like to avoid use it and insert the conditional(?) in the if statement

//create my void for choosing which
int size;
void cols(int col) {                                  
  size=(col==1 ? col1:
        col==2 ? col2:
        col==3 ? col3:col4).size() //each list has a diferent size


for (int i=0;i<4;i++)
//whatever i want to do

to resume i want these conditional inside an if statment but it doesnt recognise it as an integer.

(col==1 ? col1: col==2 ? col2: col==3 ? col3: col4).size()
1 Like

1 Like

it doesn´t do what i want.
what i need is to repet the same proces with diferent variables that are called similar, but i dont want to write massive blocks of code repiting the same proces again and again, insted, i want to kind of “automatise” it.

Every time we have a collection of variables having almost same name & datatype like: :robot:
col, col1, col2, col3, etc.

We should turn them into 1 array: cols[]. So we can use a loop to iterate over them: :bulb:

1 Like

Step 1

(Please don’t say void, it’s a function. void is just its return type.)

It’s actually good to use a function, because it puts your code into separate sections (functions) which is good. This is also one purpose of OOP (see Objects /

instead of void cols(int col) { you can use your function like this:

int cols(int col) {
   int colsLocal=0;
   return colsLocal;

And then call the function like: a = cols (i); or so.

Step 2

It’s not fully clear what you want to achieve. You have an int A and depending on A you want to get a int value B. But B is not exactly A but another value.

I think to use switch or an array is a good idea. Also map() command is similar.

What I like to mention is an array of the values B and this array uses A as an index:

int[] B_values = { 17, 27, 312, 3455 };  // B 
int i=2;                                                 // A

println ( B_values [i] );      // using A or i as an index to receive B

Step 3

Another way of doing this would be an HashMap :

(This example is String → int but we could also use int → int)

// This example is String -> int but we could also use int -> int 


// Note the HashMap's "key" is a String and "value" is an Integer
HashMap<String, Integer> hm = new HashMap<String, Integer>();

// Putting key-value pairs in the HashMap
hm.put("Ava", 1);
hm.put("Cait", 35);
hm.put("Casey", 36);

// We can access values by their key
int val = hm.get("Casey");
println("Casey is " + val);


1 Like