在我的代码中,我先分割一个字符串,然后将它们添加到这样的字符串中:
List<String> stringX = new ArrayList<String>();
但是在下一部分中,我需要检索字符串并将其转换为int []。我该如何处理?或者使用现有代码有更好的方法吗?
我曾尝试以几种不同的方式转换代码,但最终得到以下异常:ArrayIndexOutOfBoundsException和NumberFormatException。
List<String> stringX = new ArrayList<String>();
List<String> stringY = new ArrayList<String>();
public void convertString() {
String input = getString(R.string.inputString);
Pattern regex = Pattern.compile("\\((.*?)\\)");
Matcher regexMatcher = regex.matcher(input);
while (regexMatcher.find()) {
list.add(regexMatcher.group(1));
}
for (String str : list) {
String formatted = (str.replace(", ", ","));
formattedList.add(formatted);
}
String[] values = formattedList.toArray(new String[formattedList.size()]);
for (String s : values) {
String coordXY[] = s.split(",");
int x = Integer.parseInt(coordXY[0]);
int y = Integer.parseInt(coordXY[1]);
stringX.add(Integer.toString(x));
stringY.add(Integer.toString(y));
}
difference();
}
private void difference(){
// Setting the input array. These are what I need to get from the string lists
int inputX[] = { 0, 1, 4, 4, 4, 0, 3, 2, 4 };
int inputY[]= { 0, 3, 4, 2, 2, 1, 2, 3, 1 };
// Obtaining the number of records
int noOfRecordsX = inputX.length;
int noOfRecordsY = inputY.length;
// Array for storing differences
int[] differenceX = new int [noOfRecordsX];
int[] differenceY = new int [noOfRecordsY];
differenceX [0] = 0; // First record difference is 0 only
differenceY [0] = 0; // First record difference is 0 only
// Looping number of records times
for( int i=0; i < noOfRecordsX -1 ;i++)
{
// Difference = next record - current record
differenceX [i+1]= inputX [i+1] - inputX[i];
}
for( int i=0; i < noOfRecordsY -1 ;i++)
{
// Difference = next record - current record
differenceY [i+1]= inputY [i+1] - inputY[i];
}
}
答案 0 :(得分:0)
尝试一下:
private void testMethod(){
String input = "(0, 0) (1, 3) (4, 4) (4, 2) (4, 2) (0, 1) (3, 2) (2, 3) (4, 1)";
ArrayList<Integer> x = new ArrayList<>();
ArrayList<Integer> y = new ArrayList<>();
Pattern pattern = Pattern.compile("\\((.*?)\\)");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String[] sa = matcher.group(1).split(",");
x.add(Integer.valueOf(sa[0].trim()));
y.add(Integer.valueOf(sa[1].trim()));
}
}
希望您不介意我使用ArrayList<Integer>
而不是int[]
。
我确信有一些顶级RegEx专家可以在两行中完成所有这些工作,但这可以做到-而且很容易跟踪正在做的事情。