【发布时间】:2015-12-14 07:08:43
【问题描述】:
所以我必须从文本文件中提取数据。
文本文件是这样设置的。
3400 Moderate
310 Light
etc.
我需要提取数字,将它们存储在一个数组和字符串中,然后将它们存储在另一个数组中,这样我就可以根据数组中写入的内容对数字进行计算,然后将其输出到文件中。我已经完成了最后一部分,当我从 txt 中提取数据时,我只是不知道如何将整数与字符串分开。文件。
这是我现在所拥有的,但它只是将 int 和单词提取为 String。
import java.io.*;
import java.util.*;
public class HorseFeed {
public static void main(String[] args){
Scanner sc = null;
try {
sc = new Scanner(new File("C:\\Users\\Patric\\Desktop\\HorseWork.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
String[] arr = lines.toArray(new String[0]);
for(int i = 0; i< 100; i++){
System.out.print(arr[i]);
}
}
}
【问题讨论】:
-
一个解决方案是使用正则表达式:
str.matches("[a-zA-Z]+");.. 还有很多其他解决方案,如果您有问题,请尝试考虑一个并发布。 -
在空格上分割每一行(google for "how to split a String in Java")。第一个元素是 int,第二个是 word。
-
文件是制表符分隔的,还是那些空格?每行可以有多个单词吗?