日期:2014-05-20  浏览次数:20867 次

初学java,求各位大侠解疑
题目——通过命令行输入一段英文文本,分析该段文本中包含的单词数和每个单词的出现次数并输出

代码如下:
package two;
import java.util.*;

public class Word 
{
String str;
Word(String str)
{
this.str=str;
}
}
class Test
{
public static void main(String[] args) 
{
int[] times=new int[100] ;
Scanner sc=new Scanner(System.in);
ArrayList<Word> al=new ArrayList<Word>();
while(!sc.next().equals("end"))
{
Word wo=new Word (sc.next());
if(al.contains(wo))
++times[al.indexOf(wo)];
else
{al.add(wo);times[al.indexOf(wo)]++;}
}
//System.out.print("aoehg");
for(int i=0;i<al.size();i++)
{
System.out.print(al.get(i).str);
System.out.println(times[i]);
}
}
}

想不通哪出问题了!!!!!~~~~~~~

------解决方案--------------------
import java.util.ArrayList;
import java.util.Scanner;

public class Test {
String str;

Test(String str) {
this.str = str;
}

public static void main(String[] args) {
int[] times = new int[100];
Scanner sc = new Scanner(System.in);
ArrayList<Test> al = new ArrayList<Test>();
while (!sc.next().equals("end")) {
Test wo = new Test(sc.next());
if (al.contains(wo))
++times[al.indexOf(wo)];
else {
al.add(wo);
times[al.indexOf(wo)]++;
}
}
// System.out.print("aoehg");
for (int i = 0; i < al.size(); i++) {
System.out.print(al.get(i).str);
System.out.println(times[i]);
}
}

}

------解决方案--------------------
import java.util.*;

 public class Word {
public static void main(String[] args) {
String str="hello reg hello hello ";
ArrayList<String> list = new ArrayList<String>();
String[] strs=str.split(" ");
HashMap<String,Integer> hash=new HashMap<String,Integer>();
for(int i=0;i<strs.length;i++){
if(list.contains(strs[i])){
hash.put(strs[i],hash.get(strs[i])+1);
}else if(strs[i].hashCode()!=0){
list.add(strs[i]);
hash.put(strs[i], 1);
hash.put(strs[i],1);;
}
}
System.out.println("All words:"+hash.size());
System.out.println("The all words are:");
for(String s:list){
System.out.println(s+":"+hash.get(s));
}
}
}
------解决方案--------------------
探讨
请问为什么统计次数没有起到作用,al.contains(wo)似乎没起作用?