简体   繁体   English

代码不打印任何内容

[英]Code not printing anything

I am writing code that reads in a text file through the command line arguments in the main method and prints out each word in it on its own line without printing any word more than once, it will not print anything, can anyone help? 我正在编写代码,该代码通过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;
}
}

You have several problems: 您有几个问题:

  1. you're reading whole file line by line, but assign only last line to variable x 您正在逐行读取整个文件,但仅将最后一行分配给变量x
  2. you're doing 2 splits, both on regexp, it is enough 1 您正在进行2次拆分,都在regexp上,就足够1
  3. in unique - you're filling only some parts of array, other parts are null 以唯一的方式-您只填充数组的某些部分,其他部分为null

Here is shorter version of what you need: 这是您需要的简短版本:

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