split
even gets a regular expression and its is not wrong, since []
combines a single character of the contained in []
, for example to [abc]
will combine only a
, b
, or c
. In your case either use ;
or [;]
.
Assuming you need, from the input 0;1;0
, of a result like this:
0
1
0
Your problem is basically how you are recovering values after split
. This method returns a vector of characters, so you need to assign this result to any variable, for example as follows:
final String[] values = recebeMM.split("[;]");
After this, no for
, instead of iterating the characters of recebeMM
will iterate the result vector of split
. We can use an enhaced for , something like this:
for (final String value : values) {
if (value.trim().length() > 0) {
texto.append(value);
texto.append("\n\r");
}
}
Or for
default, something like this:
for (int i = 0; i < values.length; i ++) {
final String value = values[i];
if (value.trim().length() > 0) {
texto.append(value);
texto.append("\n\r");
}
}
Also note this excerpt:
if(recebeMM != " ")
Well, this will always be true
, since recebeMM
is 0;1;0
, so the only thing you're doing is taking character by character, including \n
between them and reporting as MM
.
One way to use charAt
as you used would be more or less this, then we would not need split
:
final int length = recebeMM.length();
for (int i = 0; i < length; i++) {
final char value = recebeMM.charAt(i);
if (value != ' ' && value != ';') {
texto.append(value);
texto.append("\n\r");
}
}
Another thing is that you should do the carriage return , using \r
when you are assigning the value to a JTextField
, otherwise the result will be something like 0 1 0
while making MM.getText()
. To do this, just use \n\r
instead of just \n
.
Finally a tip: always consider using StringBuilder
(or even StringBuffer
, depending on the context) instead to concatenate strings .
A version for your BenviarActionPerformed
method would be this:
private void BenviarActionPerformed(final java.awt.event.ActionEvent evt) {
final String recebeMM = MMdados.getText();
final StringBuilder texto = new StringBuilder();
final String[] values = recebeMM.split("[;]");
for (final String value : values) {
if (value.trim().length() > 0) {
texto.append(value);
texto.append("\n\r");
}
}
MM.setText(texto.toString());
}