DESKTOP-GLJFHBB_20200911-常虎科

一、问题陈述:

问题:

如何用集合实现,从控制台输入若干个单词放入集合中,将这些单词排序后输出(忽略大小写)打印出来 ?

解决过程:

    import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class WordSort {
    private Scanner scanner;
    private List<String> list;
    private  int count;
    private StringBuffer buffer;
    public WordSort( int count ) {
        super();
        if( count < 2 ) { // 不能少于两个,否则不能比较
            throw new RuntimeException( "单词个数不能少于两个" );
        }
        this.count=count;
        list = new ArrayList<String>();
        this.scanner = new Scanner( System.in );
        this.buffer= new StringBuffer();
    }
    public void scan() {
        for (int i = 0; i < count; i++) {
            System.out.println( "请输入第" + ( i + 1 )+ "个单词" );
            String str = scanner.nextLine() ;
            list.add(str);
        }
         list.sort(comparator); 
    }
    Comparator<String> comparator = new Comparator<String>() {
        @Override
        public int compare(String str1, String str2) {
            
            return str1.compareToIgnoreCase(str2);
        }   
    };
    @Override
    public String toString() {
         buffer.setLength(0);
         buffer.append("[");
        for(String s : list) {
            buffer.append(s);
            buffer.append(",");     
        }   
        int y =buffer.lastIndexOf(",");
        buffer.deleteCharAt(y);
        buffer.append("]");
        return buffer.toString();
    }
    public static void main(String[] args) {
        WordSort ws = new WordSort(3);
        ws.scan();
        System.out.println(ws.toString());
    }
    
}

toString 输出最后会多一个逗号,该如何解决?

二、每日吐槽:

加油。