02排序英文单词

java老师留下的作业

大体思想是新建一个word类重写compareTo方法

再使用Arrays工具类的sort方法进行排序。

Main类

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Word[] words = new Word[44];
        try {
            fillWords(words);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Arrays.sort(words);
        System.out.println(Arrays.toString(words));

    }

    public static void fillWords(Word[] words) throws IOException {
        System.out.println("输入文件地址");
        int choose = 0;
        String path = "";
        Scanner input = new Scanner(System.in);
        path = input.next();
        StringBuilder text = new StringBuilder();
        try {
            FileInputStream inputStream = new FileInputStream(path);
            byte[] bytes = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(bytes)) != -1) {
                text.append(new String(bytes, 0, length));
            }
            inputStream.close();
        } catch (FileNotFoundException e) {
            System.out.println(e);
            e.printStackTrace();
        }
        String s = text.toString();
        String[] wordArray = ToArray(s);
        for (int i = 0; i < words.length; i++) {
            words[i] = new Word(wordArray[i]);
        }
    }

    public static String[] ToArray(String s) {
        int head = 0;
        int count = 0;
        String keyWord = "";
        char[] letter = s.toCharArray();
        String[] keyWords = new String[100];
        for (int i = 0; i < letter.length - 1; i++) {
            if (letter[i] == ' ') {
                for (int j = head; j <= i; j++) {
                    keyWord = keyWord + letter[j];
                }
                keyWords[count++] = keyWord;
                keyWord = "";
                head = i + 1;
            }
        }
        return keyWords;
    }
}

Word类`

public class Word implements Comparable {
    private final String word;
    private final char firstChar;

    public Word(String word) {
        this.word = word;
        this.firstChar = word.charAt(0);
    }

    @Override
    public int compareTo(Object o) {
        Word word1 = (Word) o;
        return this.firstChar < ((Word) o).firstChar ? -1 : 1;
    }

    @Override
    public String toString() {
        return word;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值