我将读取文件内容作为程序的输入。
我将其存储为一个字符串并将其拆分为2个字符串。
File file = new File("question.txt");
PrintWriter pw = new PrintWriter(file);
pw.write("81 : (1,53.38,$45) (2,88.62,$98) (3,78.48,$3) (4,72.30,$76) (5,30.18,$9) (6,46.34,$48)");
pw.close();
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
Map<Integer, Object> map = new HashMap<Integer, Object>();
int i = 0;
Demo d = new Demo();
String[] part = line.split(":");
String part1 = part[0].trim();
String part2 = part[1].trim();
输入: 81 : (1,53.38,$45) (2,88.62,$98) (3,78.48,$3) (4,72.30,$76) (5,30.18,$9) (6,46.34,$48)
输出:
totalWeight = 81;
index[] = {1,2,3,4,5,6};
weight[] = {53.38,88.62,78.48,72.30,30.18,46.34};
value[] = {45,98,3,76,9,48};
第二个字符串在方括号内包含3个值。第一个数字是“索引”,第二个数字是“重量”,第三个数字是“值”。
如何将其拆分并存储到3个不同的阵列中?
我知道将其解析为具有3个数组并为其分配值的类的对象的一种方法。
但是还有更好的方法吗?
String[] part2 = part[1].replace("(", "").trim().split(")");
List<String> indices = new ArrayList<String>();
List<String> weights= new ArrayList<String>();
List<String> values = new ArrayList<String>();
for (String s : part2)
{
String item = s.split(",");
indices.add(item[0]);
weights.add(item[1]);
values.add(item[2]);
}
// to get them as arrays
String[] allWeightsArray = weights.toArray(new String[]); ...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句