【发布时间】:2014-03-20 15:49:18
【问题描述】:
从标准输入中逐行获取如下表格:
3 9 $12 $7 $2
4 $5 1 $4 $21
12 $11 0 0 $17
我需要以这种方式解析它,这样我就会有两个二维列表: 1) 只是一个数字表:
3 9 12 7 2
4 5 1 4 21
12 11 0 0 17
2) 表,其中 true 表示数字前面有一个美元符号:
false false true true true
false true false true true
false true false false true
最好的方法是什么?
我有以下代码:
public static List[] parseTable() {
ArrayList<ArrayList<Integer>> vals = new ArrayList<>();
ArrayList<ArrayList<Boolean>> truthtable = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String mark = "$";
try {
while (true) {
String[] splitline = reader.readLine().split("\\s+");
ArrayList<Integer> valsrow = new ArrayList<>();
ArrayList<Boolean> truthrow = new ArrayList<>();
System.out.println(Arrays.toString(splitline));
for (String element: splitline) {
if (element.startsWith(mark)) {
truthrow.add(true);
}
else {
truthrow.add(false);
}
valsrow.add(Integer.parseInt(el.replaceAll(mark, "")));
}
vals.add(valsrow); truthtable.add(truthrow);
}
}
catch(IOException e) {
List[] output = new List[2];
res[0] = truthtable; res[1] = vals;
return output;
}
但它没有正确去除空格并导致
NumberFormatException: for input string: ""
我初步不知道输入的大小。
【问题讨论】:
-
你肯定尝试过。展示它!
标签: java parsing input tabular