Warm tip: This article is reproduced from stackoverflow.com, please click
java knime

Java Loop with condition inside

发布于 2020-03-27 10:18:43

I am not experienced in Java, but I need to create Java snippet node in KNIME.

I am trying to write a short Loop that creates a counter/iterator based on a specific condition. I managed to write the IF THEN ELSE part but I wonder how to put it inside the Loop:

out_user_session_counter = 1;

if (c_session_end.equals("session end")) {
    out_user_session_counter = out_user_session_counter + 1; 
} else {
    out_user_session_counter = out_user_session_counter + 0;
}

The idea is: each time c_session_end.equals("session end") then out_user_session_counter should be augmented by 1

UPD.: Here is screenshot of data model with loop result (not correct result):

example screenshot

Correct expected result would be 1 1 1 1 2 2 3 3 3 3 3 instead of 1 1 1 1 11 1 11 1 1 1 1

Questioner
Milena
Viewed
144
SteveR 2019-07-04 17:30

You need the loop counter to persist between rows in the Java Snippet. To do that, you define it in the //Your custom variables: part of the snippet:

int sessionCounter=0;

Then in the //Enter you code here: part:

if("session end".equalsIgnoreCase(c_column2)){
    sessionCounter++;
}

out_user_session_counter = sessionCounter;

As shown, the row with 'session end' will contain the incremented counter. If you want it to contain the old counter, change the snippet so that the final line above is before the if statement.

You don't need to put this in a loop in KNIME - the expression part of the snippet is already calculated sequentially for each input row. Shown below in the snippet dialog for clarity

enter image description here