I have this code that gets a string written in a TextArea and passes it though a method (which allows multilines too):
String ad = ady.getText();
if (ad.matches("-?[0-9]+,-?[0-9]+") || ad.matches("-?[0-9]+,-?[0-9]+\n")) {
String[] parts = ad.split(",");
int num1 = Integer.parseInt(parts[0]);
int num2 = Integer.parseInt(parts[1]);
if (num1 <= cl.size() && num1 > 0) {
g.addCliente(nom, urba, street, ad);
} else {
JOptionPane.showMessageDialog(this, "Cliente inválido");
}
} else {
JOptionPane.showMessageDialog(this, "Formato inválido");
}
So as you can see, it already checks if the String follows a certain format "num1,num2" and num1 must be lower than size. how do i make it so it checks same format for every line in a TextArea and then passes it as: "Num1,Num2\nNum1,Num2\nNum1,Num2" with all the lines the user writes in the TextArea?
As you can see I tried adding \n at the end of ("-?[0-9]+,-?[0-9]+") and making it to be an OR if, but its not working.
Here is the answer:
String nom = nombre.getText();
String urba = urb.getText();
String street = calle.getText();
String ad = ady.getText();
String[] lines = ad.split("\n");
String adya = "";
for (String line : lines) {
if (line.matches("-?[0-9]+,-?[0-9]+")) {
String[] parts = line.split(",");
int num1 = Integer.parseInt(parts[0]);
//int num2 = Integer.parseInt(parts[1]);
if (num1 <= cl.size() && num1 > 0) {
adya += line+"\n";
} else {
JOptionPane.showMessageDialog(this, "Cliente inválido");
return;
}
} else {
JOptionPane.showMessageDialog(this, "Formato inválido");
return;
}
}
g.addCliente(nom, urba, street, adya.substring(0,adya.length()-1));
last line removes the last "\n" when passing it trough the method.