繁体   English   中英

代码不打印任何内容

[英]Code not printing anything

我正在编写代码,该代码通过main方法中的命令行参数读取文本文件,并在自己的行上打印出每个单词,而不会多次打印任何单词,它不会打印任何内容,有人可以帮忙吗?

import java.util.*;
import java.io.*;
public class Tokenization {
public static void main(String[] args) throws Exception{
String x = "";
String y = "";

File file = new File(args[0]);
Scanner s = new Scanner(file);



String [] words = null;
while (s.hasNext()){
x = s.nextLine();
}
words = x.split("\\p{Punct}");


String [] moreWords = null;
for (int i = 0; i < words.length;i++){
    y = y + " " + words[i];
}
moreWords = y.split("\\s+");


String [] unique = unique(moreWords);
for (int i = 0;i<unique.length;i++){
    System.out.println(unique[i]);
}
s.close();
}



public static String[] unique (String [] s) {
String [] uniques = new String[s.length];
for (int i = 0; i < s.length;i++){
    for(int j = i + 1; j < s.length;j++){
        if (!s[i].equalsIgnoreCase(s[j])){
        uniques[i] = s[i];  
        }
    }
}
return uniques;
}
}

您有几个问题:

  1. 您正在逐行读取整个文件,但仅将最后一行分配给变量x
  2. 您正在进行2次拆分,都在regexp上,就足够1
  3. 以唯一的方式-您只填充数组的某些部分,其他部分为null

这是您需要的简短版本:

import java.io.File;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Tokenization {
    public static void main(String[] args) throws Exception {
        Set<String> words = new HashSet<String>();
        try {
            File file = new File(args[0]);
            Scanner scanner = new Scanner(file);
            while (scanner.hasNext()) {
                String[] lineWords = scanner.nextLine().split("[\\p{Punct}\\s]+");
                for (String s : lineWords)
                    words.add(s.toLowerCase());
            }
            scanner.close();
        } catch (Exception e) {
            System.out.println("Cannot read file [" + e.getMessage() + "]");
            System.exit(1);
        }

        for (String s : words)
            System.out.println(s);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM