以表格形式显示

时间:2011-03-10 04:04:31

标签: java

这是我的计算术语频率的代码。

System.out.println("Please enter the required word  :");
    Scanner scan = new Scanner(System.in);
    String word = scan.nextLine();
    String[] array = word.split(" ");
    int filename = 11;
    String[] fileName = new String[filename];
    int a = 0;

    for (a = 0; a < filename; a++) {
        try {
            File file = new File(
                    "C:\\Users\\user\\fypworkspace\\TextRenderer\\abc" + a
                            + ".txt");
            System.out.println("File = abc" + a + ".txt");
            for (int i = 0; i < array.length; i++) {

                System.out.println(array[i]);

                int totalCount = 0;
                int wordCount = 0;
                int numDoc2 = 0;

                Scanner s = new Scanner(file);
                {
                    while (s.hasNext()) {
                        totalCount++;
                        if (s.next().equals(array[i]))
                            wordCount++;

                    }

                    System.out.println("Word count:  " + wordCount);
                    System.out.println("Total count: " + totalCount);
                    System.out.printf("Term Frequency:   %8.4f",
                            (double) wordCount / totalCount);

                    System.out.println("\n");

                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("File is not found");

        }

    }

到目前为止代码显示

请输入所需的字词: 约

File = abc0.txt

字数:0

总数:1706

学期频率:0.0000

File = abc1.txt

字数:0

总数:9819

学期频率:0.0000

如何创建数据表格式,如下所示:

输出:

文件名字总词汇

abc0.txt 0.1 0.2 0.3

abc1.txt 0.4 0.5 0.6

3 个答案:

答案 0 :(得分:0)

不使用System.out.println(String),而是使用System.out.print(String)

System.out.print(String)将打印出数据,而不会导致下一行System.out.print(String)启动。这将帮助您以正确的格式输出数据

将顶部文件名的print语句更改为

System.out.print("abc" + a + ".txt");

AND将最后的打印语句更改为

System.out.print(" " + wordCount);
System.out.print(" " + totalCount);
System.out.printf(" %8.4f", (double) wordCount / totalCount);
System.out.println();

答案 1 :(得分:0)

您可以使用System.out.print();代替System.out.println();并通过“\ t”提供正确的TAB

示例: 查看每种情况的差异

System.out.print("Hello ");  
System.out.print("World");    
//output: Hello World

System.out.println("Hello ");  
System.out.println("World");    
//output: 
     Hello 
     World

答案 2 :(得分:0)

使用System.out.format,内部使用Formatter