我有一个包含以下数据的文本文件:
20;
1: 39, 63;
2: 33, 7;
16: 33, 7;
3: 45, 27;
4: 8, 67;
5: 19, 47;
6: 15, 40;
...
20: 65, 54;
第一个整数是列表中的条目数量。
每一行都是一个条目。因此条目 1 的 x y 坐标分别为 39 和 63。
我知道我可以使用不同的分隔符来读取数据,但我不太确定如何实现这一点。目前我正在使用 split()
。
下面的代码读取每一行,但这显然不起作用,因为分隔符设置不正确。有没有好的方法让它发挥作用?
String[] temp = sc.next().split(";");
int productAmount = Integer.parseInt(temp[0]);
sc.nextLine();
for (int i = 0; i < productAmount; i++) {
int productID = sc.nextInt();
int x = sc.nextInt();
int y = sc.nextInt();
Product product = new Product(x, y, productID);
productList.add(product);
}
最佳答案
所有标记在删除最后一个字符后都可以转换为整数。您可以利用给定数据的此属性。定义一个这样的方法:
int integerFromToken(String str) {
return Integer.valueOf(str.substring(0, str.length() - 1));
}
返回 token 的整数部分(39,
返回39
,63;
返回63
等.)。现在使用该方法从标记中获取整数值(通过 sc.next()
获取):
int productID = integerFromToken(sc.next());
int x = integerFromToken(sc.next());
int y = integerFromToken(sc.next());
关于java - JAVA中使用扫描仪和多个分隔符从文本文件中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19694710/