【发布时间】:2014-03-06 01:52:24
【问题描述】:
我有一个包含 50 个不同长度和内容的字符串行的文本文件。我需要读取文件并按升序排序。排序条件:句子中以字母“a”开头的单词个数。
public static void main(String[] args) throws FileNotFoundException {
String token1 = "";
Scanner inFile1 = new Scanner(new File("E:\\text.txt"));
List<String> temps = new LinkedList<String>();
inFile1.useDelimiter(". ");
while (inFile1.hasNext()) {
token1 = inFile1.nextLine();
temps.add(token1);
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
for (int i = 0; i < tempsArray.length; i++) {
System.out.println(tempsArray[i]);
}
int cnt = 0; //number of words in the string line
for (int i=0; i<tempsArray.length; i++) {
int k=0; //number of words that start from the letter "а"
System.out.println("Line № = " + i);
StringTokenizer st = new StringTokenizer(tempsArray[i]);
while (st.hasMoreTokens()) {
cnt++;
String s= st.nextToken();
if (s.charAt(0)=='a') {
k++;
}
}
System.out.println("Number of words = " + cnt);
cnt=0;
System.out.println("Number of words 'а' = " + k);
}
}
我按照 Kau 的建议使用 Map。但是Map 使用唯一键。但我的 K 可以有相同的值,Map 找不到合适的字符串元素。我还能用什么Сollection?
【问题讨论】: