JAVA - 双拆分字符串并转换为整数

JAVA - Double split string and convert to integer

你好,我尝试了很多方法来完成这个,但我失败了。 你可以帮帮我吗 ? 我需要双拆分,一个是“\n”,第二个是“|”。 在 textArea 中是字符串 350|450\n 444|452\n 等等。 有鼠标坐标。 X|Y 在 int 数组中我需要

array[0]= x coord;
array[1]= y coord;
array[2]= x coord;
array[2]= y coord;

所以我在 textarea.I 中有字符串,用 "\n"

拆分
String s[]= txtArea.getText().split("\n");

这是一个拆分,在 textarea 中我有类似 150|255 的内容 这是我的鼠标坐标 x|y。 所以我需要下一个拆分“|”。

String s2[] = s[i].split("|");

之后

int [] array = new [s.length*2];

以及

的一些方法
while(!(s[j].equals("|")))
array[i] = Integer.parseInt(s[j]);

我试过类似的东西-

for(String line : txtArea.getText().split("\n")){
            arrayXY = line.split("\|");
            array = new int[arrayXY.length];
        }

非常感谢您的回答:) 祝你有个愉快的一天。

这可以使用正则表达式轻松解决:

String[] split = input.split("\||\n");

split 将包含输入中的单个数字。

使用Scanner. It is always preferred over String.split().

您的代码将减少为:

Scanner scanner = new Scanner(txtArea.getText());
scanner.useDelimiter("\||\n");          // i.e. | and the new line
for (int i = 0; i < array.length; i++) {  // or use the structure you need
    array[i] = scanner.nextInt();
}

还有,别忘了import java.util.Scanner;