我正在尝试创建一个读取未经过字母顺序的书目文本文件的程序,然后打印出新的按字母顺序排列的文本文件。我已经达到了我的程序识别每行的第一个字母(我打印出来以确定)的程度,但我不知道如何实现代码,以便程序可以按字母顺序重新排列行。
这是我更新的代码而不使用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: ");
}
}
答案 0 :(得分:2)
为什么不使用sort?
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
}