[英]Check if multi-line String contain only 2 numbers separated by 1 comma in Java
I have this code that gets a string written in a TextArea and passes it though a method (which allows multilines too):我有这段代码,它获取一个写入 TextArea 的字符串并将其传递给一个方法(也允许多行):
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.如您所见,它已经检查了字符串是否遵循某种格式“num1,num2”,并且 num1 必须小于 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?
我如何使它检查 TextArea 中每一行的相同格式,然后将其传递为:“Num1,Num2\nNum1,Num2\nNum1,Num2”以及用户在 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.如您所见,我尝试在 ("-?[0-9]+,-?[0-9]+") 的末尾添加 \n 并使其成为 OR if,但它不起作用。
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.最后一行在通过方法传递它时删除最后一个“\ n”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.