1

我正在尝试创建一个程序,该程序读取未按字母顺序排列的书目文本文件,然后打印出新按字母顺序排列的文件。我已经到了我的程序可以识别每行的第一个字母的程度(我打印出来是肯定的),但我不知道如何实现代码,以便程序可以按字母顺序重新排列行。

这是我没有使用 displayCorrectBib 方法的更新代码,但我仍然没有输出:

package hw6;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Hw6 {

    public static void main(String[] args) throws Exception {
//read in a works cited text file
        BufferedReader fin = new BufferedReader(new FileReader("Bibliography.txt"));

//        String line = null;  

        displayIncorrectBib(fin);

        ArrayList<String> lines = new ArrayList<String>();

        while ((line = fin.readLine()) != null) {
            lines.add(line);
        }

        Collections.sort(lines);

        for (String s : lines) {
            System.out.println(s);
        }

        displayCorrectBib(lines);


        fin.close();                //close BufferedReader
    }
    public static String line;
    public static char[] stringArray;

    public static void displayIncorrectBib(BufferedReader fin) throws Exception {

        System.out.println("Incorrectly Alphabetized Bibliography:");

        while ((line = fin.readLine()) != null) {

            toChar(line);                            //call toChar to convert string to char

            System.out.println(line);             //print unalphabetized bibliography on separate lines

        }
        System.out.println();

    }
    public static char[] letters = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
        'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

    public static char toChar(String line) {
        //convert string line to character array
        stringArray = line.toCharArray();

        System.out.println(stringArray[0]);

        return stringArray[0];
    }

    public static void displayCorrectBib(List<String> lines) {
        System.out.println("Correctly alphabetized Bibliography: ");


    }
}
4

1 回答 1

2

为什么不只使用排序?

ArrayList<String> lines = new ArrayList<String>();
String line;
while ((line = fin.readLine()) != null) {
       lines.add( line );
}

Collections.sort(lines);

并显示:

public static void displayCorrectBib( List<String> lines ) {
    for( String s : lines )
    {
        System.out.println(s);
    }
}

这是完整的形式:

 public static void main(String[] args) throws Exception {
    //read in a works cited text file
    BufferedReader fin = new BufferedReader(new FileReader("Bibliography.txt"));

    ArrayList<String> lines = new ArrayList<String>();
    String line;
    while ((line = fin.readLine()) != null) {
        lines.add( line );
    }

    Collections.sort(lines);

    for( String s : lines )
    {
        System.out.println(s);
    }

    fin.close();                //close BufferedReader
}
于 2013-06-28T17:42:26.407 回答