I try to create a class in which there is a text field and a field with a number, but when I try to link them through a lambda expression, I get a message that the field must be final or effectively final.

class Stranica{ private final int[][] kolichestvo = new int[24][4]; private TextField[][] tfPolVvod = new TextField[24][4]; { for (int i = 0; i < 24; i++) { for (int j = 0; j < 4; j++) { TextField tf = new TextField(); tf.setPrefWidth(50); tf.setOnKeyReleased(pdj ->{ if(!tf.getText().matches("\\d+")){ tf.setText("0"); tf.selectAll(); //в следующей строке будет ругаться на то что поле не финальное }else kolichestvo[i][j]=Integer.parseInt(tf.getText()); }); tfPolVvod[i][j]=tf; } } } } 

Tell me how to connect them correctly.

  • Try to put the word final before initializing the kolichestvo and tfPolVvod fields - Werder
  • @Werder tried the same error. - arachnoden
  • one
    Could you tell me what condition you set for implementation? Lambda you should put the FOR loop into another method and then transfer the values ​​to it. - Oleg Grechishkin
  • @OlegGrechishkin described below under the first answer, if my code can be improved, tell me how. - arachnoden

1 answer 1

This is how such issues are resolved:

 class Stranica { private final int[][] kolichestvo = new int[24][4]; private TextField[][] tfPolVvod = new TextField[24][4]; { for (int i = 0; i < 24; i++) { for (int j = 0; j < 4; j++) { final int ii =i; final int jj =j; TextField tf = new TextField(); tf.setPrefWidth(50); tf.setOnKeyReleased(pdj ->{ if(!tf.getText().matches("\\d+")){ tf.setText("0"); tf.selectAll(); }else kolichestvo[ii][jj]=Integer.parseInt(tf.getText()); }); tfPolVvod[i][j]=tf; } } } } 

but for reference, something with this part of the code is clearly wrong ...

  • We need a class in which there would be an array of numbers, and text fields of the language, with this array, when entering a number into the field, it is automatically recorded in the desired slot of the array. Is it possible to implement it somehow easier? - arachnoden
  • one
    If all conditions known to me are constant, then it is easier to implement it. But from the point of view of support, expansion and other life situations associated with your code, there is a sea of ​​unrealized opportunities. - Peter Slusar