Java 计算文件的字数并将其存储在数组中?
再说一遍。我要再问一次关于计算单词以及如何将其存储在数组中的问题。到目前为止,我得到的只是这个Java 计算文件的字数并将其存储在数组中?,java,Java,再说一遍。我要再问一次关于计算单词以及如何将其存储在数组中的问题。到目前为止,我得到的只是这个 Scanner sc = new Scanner(System.in); int count; void readFile() { System.out.println("Gi navnet til filen: "); String filNavn = sc.next(); try{ File k = new File(filNavn); Scanner sc2 = n
Scanner sc = new Scanner(System.in);
int count;
void readFile() {
System.out.println("Gi navnet til filen: ");
String filNavn = sc.next();
try{
File k = new File(filNavn);
Scanner sc2 = new Scanner(k);
count = 0;
while(sc2.hasNext()) {
count++;
sc2.next();
}
Scanner sc3 = new Scanner(k);
String a[] = new String[count];
for(int i = 0;i<count;i++) {
a[i] =sc3.next();
if ( i == count -1 ) {
System.out.print(a[i] + "\n");
}else{
System.out.print(a[i] + " ");
}
}
System.out.println("Number of words: " + count);
}catch(FileNotFoundException e) {
Scanner sc=新扫描仪(System.in);
整数计数;
void readFile(){
System.out.println(“Gi navnet til filen:”);
字符串filNavn=sc.next();
试一试{
文件k=新文件(filNavn);
扫描仪sc2=新扫描仪(k);
计数=0;
while(sc2.hasNext()){
计数++;
sc2.next();
}
扫描仪sc3=新扫描仪(k);
字符串a[]=新字符串[计数];
对于(int i=0;i,这里有一个更简单的方法:
public static void main(String[] args){
File f= new File(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String line = null;
String[] res;
while((line = br.readLine())!= null ){
String[] tokens = line.split("\\s+");
String[] both = ArrayUtils.addAll(res, tokens);
}
}
HashSet是一个选项吗?您可以使用Arrays.copyOf(Object[],int)
方法在遇到字符串时为另一个字符串添加空间。这就是ArrayList
的工作方式。使用ArrayList存储单词,并使用BuffereReader使用readline()逐行读取文件
函数和将它们拆分为数组中的单词。此外,对于计算唯一的单词,如@Pshemo所述,您可以使用HashSet。HashSet是一个集合,没有重复的eny元素。因此,您的HashSet的大小将是count。我们不允许使用HashSet、map和arraylisty。您可以使用“contains”mathod in before insertion.help。如果我不知道数组的大小,该怎么办?我正在尝试修改上面的代码。我找到了这个。System.out.println(“Gi navnet til filen:”;String filNavn=sc.nextLine();File k=new File(filNavn);try{Scanner sc3=new Scanner(k)。使用分隔符(\\s+);String[]a=k.length();对于(int i=0;i@EdgarMiguelSantosCuevas为什么你们甚至需要在文件上使用扫描仪?