有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何创建word SortaryList

我把句子分成从课文中收到的单词,在新课文中打印单词和频率

我该如何安排单词?我很想去,但还是缺乏基础知识
请告诉我们您需要在源代码中修复的部件,我们将不胜感激

import java.io.File;  
import java.io.FileNotFoundException;  
import java.util.Scanner;

class Item {

    protected String word;
    protected int frequency;

    public Item(String word, int frequency) {
        this.word = word;
        this.frequency = frequency;
    }

    public Item() {
        this("", 0);
    }
}

class SortedArrayList {

    protected Item[] items;
    private int size = 0;
    private int maxSize = 10;

    public SortedArrayList() {
        items = new Item[maxSize];
    }

    public SortedArrayList(int max) {
        items = new Item[max];
        maxSize = max;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        return size == maxSize;
    }

    public void insert(Item item) {
        if (isFull())
            resize();
        else if (isEmpty()) {
            items[0] = item;
            size++;
        } else if (items[size - 1].word == item.word) {
            for (int i = size - 1; i >= 0 && (items[i].word == item.word); i--) {
                items[i + 1] = items[i];
                items[i] = item;
            }
            size++;
        } else {
            items[size] = item;
            size++;
        }

    }

    public void addFrequency(Item item) {
        for (int i = 0; i < size; i++)
            if (items[i].word == item.word)
                items[i].frequency++;
    }

    public void resize() {
        Item[] resizeItems = new Item[2 * items.length];
        for (int i = 0; i < items.length; i++) {
            resizeItems[i] = items[i];
        }
        items = resizeItems;
        maxSize *= 2;
    }

    public void print(int i) {
        System.out.println(items[i].word + "\t" + items[i].frequency);
    }
}

public class WordFrequency {

    public static void main(String[] args) throws FileNotFoundException {
        SortedArrayList[] list = new SortedArrayList[10];
        for (int i = 0; i < list.length; i++) {
            list[i] = new SortedArrayList();
        }
        String fileName = "sample.txt";
        Scanner inFile = null;
        inFile = new Scanner(new File(fileName));
        String lineString;

        while (inFile.hasNextInt()) {
            lineString = inFile.nextLine();
            String[] array = lineString.split(" ");
            for (int i = 0; i < array.length; i++) {
                Item it = new Item(array[i], 1);
                list[i].insert(it);
                list[i].addFrequency(it);
            }
            for (int i = 0; i < list.length; i++) {
                list[i].print(i);
            }
        }
        inFile.close();

    }
}

如果“sample.txt”的内容与以下内容相同

apple orange grape apple peach apple

期望的结果

apple 3  
grape 1  
orange 1   
peach 1  
word:4 frequencies:6

共 (0) 个答案