我正在从文件中读入,输入如下:
Description (1.0,2.0) (2,7.6) (2.1,3.0)
Description2 (4,1)
...
Description_n (4,18) (8, 7.20)
我希望能够取出括号内的数字并将它们从字符串转换为数字,以便我可以对它们进行数学运算。现在,为了简化事情,我的代码只读取第一行,然后根据空格将其分割:
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File("filename.txt")));
//reader reads in the first line
String firstLine = reader.readLine();
//splits into an array of ["Description","(1.0,2.0)","(2,7.6)","(2.1,3.0)"]
String[] parts = first.split(" ");
//now I want to store 1.0, 2, and 2.1 in one array as ints and 2.0, 7.6, and 3.0 in another int array
} catch (Exception e) {
System.exit(0);
}
有哪些方法可以将括号内的数字存储到两个单独的整数数组中(请参阅上面的评论)?我是否应该使用正则表达式以某种方式捕获“( [1-9.] , [1-9.] )”形式的内容,然后将它们传递到另一个函数中,该函数然后将一对中的第一个数字与第二个数字分开然后将它们都转换为整数?我对 Java 中的正则表达式解析很陌生,所以我不确定如何实现它。
或者有没有一种简单、更好的方法来做到这一点?
最佳答案
这会将数字存储到Double
中-数组(不是二维数组,Double
对象的数组),因为有些有.#
。 int 数组将消除小数点后部分。
它使用正则表达式\b([\d.]+)\b
查找每个括号组中的每个数字,将每个数字添加到 ArrayList<Double>
。请注意,它假设所有输入都是完美的(不像 (bogus,3.2)
。然后该列表被转换为 Double
对象的数组。
这将为您实现目标提供良好的开端。
import java.util.Arrays;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
<P>{@code java DoubleInParenStringsToArrays}</P>
**/
public class DoubleInParenStringsToArrays {
public static final void main(String[] ignored) {
String input = "(1.0,2.0) (2,7.6) (2.1,3.0)";
String[] inputs = input.split(" ");
//"": Dummy string, to reuse matcher
Matcher mtchrGetNums = Pattern.compile("\\b([\\d.]+)\\b").matcher("");
for(String s : inputs) {
ArrayList<Double> doubleList = new ArrayList<Double>();
mtchrGetNums.reset(s);
while(mtchrGetNums.find()) {
//TODO: Crash if it's not a number!
doubleList.add(Double.parseDouble(mtchrGetNums.group(0)));
}
Double[] doubles = doubleList.toArray(new Double[doubleList.size()]);
System.out.println(Arrays.toString(doubles));
}
}
}
输出:
[C:\java_code\]java DoubleInParenStringsToArrays
[1.0, 2.0]
[2.0, 7.6]
[2.1, 3.0]
关于Java - 将字符串转换为数字的想法(正则表达式/解析/等)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22241812/