Java snippet (simple) if statements and return doesnt work

Why isn’t the following code working as expected in my Java Snippet (simple) node in KNIME? It seems to be completely non-functional, as all the rows in the ‘cat’ variable are empty. Could someone please help identify any potential errors in my approach? I’m using this code in a Java Snippet (simple) node. Here is the database structure I’m working with:

col1 = a,a,b,b,b,c,c,c,a,b,c
col2 = 01,01,02,02,03,03,01,01,02,02,03
cat =

// Define the groups g1 and g2 as arrays
String[] g1 = {"a", "b"};
String[] g2 = {"01", "02"};

// Get the current values of columns col1 and col2
String col1 = $col1$;
String col2 = $col2$;

// Check if col1 is in group g1
boolean col1InG1 = false;
for (String value : g1) {
    if (value.equals(col1)) {
        col1InG1 = true;
        break;
    }
}

// Check if col2 is in group g2
boolean col2InG2 = false;
for (String value : g2) {
    if (value.equals(col2)) {
        col2InG2 = true;
        break;
    }
}

// Assign values to cat based on conditions
if (col1InG1 && col2InG2) {
    return $cat$ = "both";
} else if (col1InG1) {
    return $cat$ = "only one";
} else if (col2InG2) {
    return $cat$ = "only two";
} else {
    return $cat$ = "none";
}

Hi @mcordoba , what column are you actually telling java snippet (simple) to return at the bottom of the window?

Your code should just be something like this:

// Assign values to cat based on conditions
if (col1InG1 && col2InG2) {
    return  "both";
} else if (col1InG1) {
    return  "only one";
} else if (col2InG2) {
    return  "only two";
} else {
    return  "none";
}

and you’d specify the return column in the selection fields at the bottom of the config dialog.

It should look like this:

If the “cat” column already exists then of course set it to replace instead of append.

If that’s still not sorting the problem, then please upload a very small workflow containing the data table and the java snippet (simple) node, so any other potential problems can be identified.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.