PrintWriter方法

时间:2017-11-06 22:45:29

标签: java arrays sorting file-io

与我的问题有关的代码功能的主要摘要: 代码采用一系列的会议成员,并用两种不同的方法对它们进行排序;一个按名字排序,一个按平均支持率排序。然后代码将两个新排序的数组输出到txt文件中。

我正在处理的问题是我似乎无法追查的错误。在我的主类中,我在void outputTxt方法中输出数据,似乎当我第一次尝试按字母顺序输出数组时,它会以数字方式输出数组,即使我在参数中单独调用它们。试图追踪所有事情,我完全不知道这是怎么回事。

主类(意外隐瞒进口,没什么大不了的):

public class CongressMembersTest {

private static final int MEMBERS = 53;

// Declaration of main object array, and file and scanner objects
private static CongressMembers[] members;
private static File inputFile;
private static File outputFile;
private static Scanner reader;
private static FileWriter fWriter;
private static PrintWriter pWriter;

// Main method
public static void main(String[] args) {
    // Initializations
    members = new CongressMembers[MEMBERS];
    try {
        inputFile = new File("approval.txt");
        reader = new Scanner(inputFile);
    } catch (FileNotFoundException ex) {
        System.out.println("File not found");
        System.exit(0);
    }

    /***********************************************************
     * Transfer from .txt to main object array Loops line by line, splitting
     * each line into strings at every blank space (or multiple spaces), and
     * putting every string into an array then plugs the array into a new
     * CongressMember object, whilst putting the object into the main object
     * array.
     *********************************************************/
    int count = 0; // keeps count of line of .txt file
    while (reader.hasNextLine()) {
        String temp = new String(reader.nextLine());
        String[] tempArr = temp.split("\\s+");
        for (int i = 0; i < tempArr.length - 6; i += 7) {
            members[count] = new CongressMembers(tempArr[i] + " " + tempArr[i + 1], tempArr[i + 2], tempArr[i + 3],
                    tempArr[i + 4], tempArr[i + 5], tempArr[i + 6]);
        }
        count++;
    }

    // call output file method
    try {
        outputTxt(sortByFirstName(members), sortByApprovalRating(members));
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("File output failed.");
        System.exit(0);
    }
}

// Returns array of congress member objects sorted alphabetically by first
// name
public static CongressMembers[] sortByFirstName(CongressMembers[] array) {
    CongressMembers temp;
    for (int i = 0; i < array.length - 1; i++) {
        for (int j = 0; j < array.length - i - 1; j++) {
            if (array[j + 1].getName().compareTo(array[j].getName()) < 0) {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }
    return array;

}

// Returns array of congress member objects by average approval rating
// (highest to lowest)
public static CongressMembers[] sortByApprovalRating(CongressMembers[] array) {
    CongressMembers temp;
    for (int i = 0; i < array.length - 1; i++) {
        for (int j = 0; j < array.length - i - 1; j++) {
            if (array[j + 1].getAvgApprovalRating() > array[j].getAvgApprovalRating()) {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }
    return array;

}

// Void method handling the writing of the main object array into a .txt
// file
public static void outputTxt(CongressMembers[] alphArr, CongressMembers[] numArr) throws IOException {
    outputFile = new File("output.txt");
    fWriter = new FileWriter(outputFile);
    pWriter = new PrintWriter(fWriter);

    // outputs total congress members
    pWriter.println("Total number of congress members: " + MEMBERS);
    pWriter.println(); // line to make .txt file neater

    // outputs alphabetically sorted members first
    pWriter.println("Congress members sorted by first name:");
    for (int i = 0; i < alphArr.length; i++) {
        pWriter.println(alphArr[i]);
    }

    // separates lists with two blank lines
    pWriter.println();
    pWriter.println();

    // outputs numerically sorted members
    pWriter.println("Congress members sorted by average approval rating (highest to lowest):");
    for (int i = 0; i < numArr.length; i++) {
        pWriter.println(numArr[i]);
    }

    pWriter.close();
}

}

国会议员对象:

public class CongressMembers {

    // private instance variables
    private String name;
    private float rating1, rating2, rating3, rating4, rating5;

    // class constructor
    public CongressMembers(String name, String rating1, String rating2, String rating3, String rating4,
            String rating5) {
        this.name = name;
        this.rating1 = Float.parseFloat(rating1);
        this.rating2 = Float.parseFloat(rating2);
        this.rating3 = Float.parseFloat(rating3);
        this.rating4 = Float.parseFloat(rating4);
        this.rating5 = Float.parseFloat(rating5);
    }

    // when obj called in println, prints name and 5 approval ratings, each
    // seperated by space
    public String toString() {
        return (this.getName() + " " + getApprovalRating1() + " " + getApprovalRating2() + " " + getApprovalRating3()
                + " " + getApprovalRating4() + " " + getApprovalRating5());
    }

    // returns average of approval ratings from last 5 months
    public float getAvgApprovalRating() {
        return (rating1 + rating2 + rating3 + rating4 + rating5) / 5;
    }

    // all getters & setters beyond this point
    public float getApprovalRating1() {
        return rating1;
    }

    public void setApprovalRating1(float approvalRating1) {
        this.rating1 = approvalRating1;
    }

    public float getApprovalRating2() {
        return rating2;
    }

    public void setApprovalRating2(float approvalRating2) {
        this.rating2 = approvalRating2;
    }

    public float getApprovalRating3() {
        return rating3;
    }

    public void setApprovalRating3(float approvalRating3) {
        this.rating3 = approvalRating3;
    }

    public float getApprovalRating4() {
        return rating4;
    }

    public void setApprovalRating4(float approvalRating4) {
        this.rating4 = approvalRating4;
    }

    public float getApprovalRating5() {
        return rating5;
    }

    public void setApprovalRating5(float approvalRating5) {
        this.rating5 = approvalRating5;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Output.txt文件(注意:平均支持率排序让Mark DeSaulnier排在最前面,而Pete Aguilar排在最后,所以我面临的唯一问题是第一个列表...它按平均支持率和不是名字):

Total number of congress members: 53

Congress members sorted by first name:
Mark DeSaulnier 93.55 86.71 78.45 97.53 94.05
Raul Ruiz 96.42 84.73 83.04 78.27 98.49
Maxine Waters 96.56 79.91 87.86 85.04 87.92
John Garamendi 99.06 96.32 78.46 95.18 62.1
Zoe Lofgren 87.83 76.91 90.75 99.05 64.67
Doug LaMalfa 81.73 99.71 87.65 52.25 93.67
Mike Thompson 69.09 82.52 97.21 63.48 99.85
Karen Bass 80.82 98.77 59.06 82.37 89.78
Grace Napolitano 66.05 98.92 98.31 70.76 76.75
Nanette Barragan 90.98 92.13 83.23 65.79 75.14
Jim Costa 82.23 92.48 57.69 77.43 96.07
Judy Chu 94.59 56.98 92.01 64.86 96.2
Jerry McNerney 99.2 73.27 77.02 89.78 59.9
Eric Swalwell 95.62 60.37 85.13 84.87 72.2
Ted Lieu 71.08 99.32 58.12 99.49 66.95
Mark Takano 63.25 82.62 98.0 59.55 89.65
Juan Vargas 71.21 66.72 84.94 82.18 82.6
Steve Knight 92.75 62.57 63.59 79.74 85.38
Ro Khanna 58.55 92.7 76.13 82.42 72.36
Jeff Denham 77.33 58.76 56.22 95.48 93.76
Paul Cook 60.22 89.22 53.76 81.71 95.85
Brad Sherman 80.65 70.25 65.57 64.98 99.24
Devin Nunes 77.11 61.05 94.16 84.33 62.62
Nancy Pelosi 68.64 86.85 86.74 85.41 51.52
Jared Huffman 65.69 73.85 83.56 79.86 74.38
David Valadao 56.47 90.47 94.8 54.06 81.52
Susan Davis 80.62 68.17 78.94 62.13 87.26
Duncan Hunter 68.7 59.69 91.67 99.81 55.31
Lou Correa 64.66 63.21 58.47 89.86 97.35
Scott Peters 56.33 86.54 67.79 92.35 70.35
Darrell Issa 95.29 55.98 64.08 73.77 83.44
Dana Rohrabacher 59.09 65.62 91.78 63.56 91.59
Tom McClintock 73.36 94.41 68.75 63.74 70.72
Salud Carbajal 77.35 89.95 57.63 69.46 74.01
Alan Lowenthal 78.73 61.71 69.45 91.64 65.64
Doris Matsui 52.0 78.32 99.45 50.14 83.54
Norma Torres 75.64 56.46 74.14 97.11 59.17
Ed Royce 89.49 71.98 63.61 74.96 61.16
Lucille Roybal-Allard 73.64 54.58 93.5 65.22 74.25
Kevin McCarthy 71.28 66.23 58.92 83.22 78.13
Jackie Speier 82.85 59.65 66.78 50.04 98.21
Adam Schiff 82.29 73.24 60.37 67.96 72.25
Anna Eshoo 59.12 92.06 54.39 64.6 85.05
Ami Bera 65.09 55.25 73.38 99.05 59.08
Julia Brownley 54.7 50.72 70.13 93.5 82.01
Ken Calvert 68.94 76.28 70.85 64.08 68.66
Barbara Lee 58.47 79.48 56.16 95.09 57.87
Tony Cardenas 99.86 52.14 69.72 71.18 52.36
Mimi Walters 85.5 67.32 54.38 68.05 69.33
Linda Sanchez 65.15 52.96 92.11 51.61 79.65
Jimmy Panetta 62.86 66.83 69.74 72.33 65.58
Jimmy Gomez 60.11 94.61 63.18 55.07 56.89
Pete Aguilar 66.96 68.56 61.09 54.29 73.53


Congress members sorted by average approval rating (highest to lowest):
Mark DeSaulnier 93.55 86.71 78.45 97.53 94.05
Raul Ruiz 96.42 84.73 83.04 78.27 98.49
Maxine Waters 96.56 79.91 87.86 85.04 87.92
John Garamendi 99.06 96.32 78.46 95.18 62.1
Zoe Lofgren 87.83 76.91 90.75 99.05 64.67
Doug LaMalfa 81.73 99.71 87.65 52.25 93.67
Mike Thompson 69.09 82.52 97.21 63.48 99.85
Karen Bass 80.82 98.77 59.06 82.37 89.78
Grace Napolitano 66.05 98.92 98.31 70.76 76.75
Nanette Barragan 90.98 92.13 83.23 65.79 75.14
Jim Costa 82.23 92.48 57.69 77.43 96.07
Judy Chu 94.59 56.98 92.01 64.86 96.2
Jerry McNerney 99.2 73.27 77.02 89.78 59.9
Eric Swalwell 95.62 60.37 85.13 84.87 72.2
Ted Lieu 71.08 99.32 58.12 99.49 66.95
Mark Takano 63.25 82.62 98.0 59.55 89.65
Juan Vargas 71.21 66.72 84.94 82.18 82.6
Steve Knight 92.75 62.57 63.59 79.74 85.38
Ro Khanna 58.55 92.7 76.13 82.42 72.36
Jeff Denham 77.33 58.76 56.22 95.48 93.76
Paul Cook 60.22 89.22 53.76 81.71 95.85
Brad Sherman 80.65 70.25 65.57 64.98 99.24
Devin Nunes 77.11 61.05 94.16 84.33 62.62
Nancy Pelosi 68.64 86.85 86.74 85.41 51.52
Jared Huffman 65.69 73.85 83.56 79.86 74.38
David Valadao 56.47 90.47 94.8 54.06 81.52
Susan Davis 80.62 68.17 78.94 62.13 87.26
Duncan Hunter 68.7 59.69 91.67 99.81 55.31
Lou Correa 64.66 63.21 58.47 89.86 97.35
Scott Peters 56.33 86.54 67.79 92.35 70.35
Darrell Issa 95.29 55.98 64.08 73.77 83.44
Dana Rohrabacher 59.09 65.62 91.78 63.56 91.59
Tom McClintock 73.36 94.41 68.75 63.74 70.72
Salud Carbajal 77.35 89.95 57.63 69.46 74.01
Alan Lowenthal 78.73 61.71 69.45 91.64 65.64
Doris Matsui 52.0 78.32 99.45 50.14 83.54
Norma Torres 75.64 56.46 74.14 97.11 59.17
Ed Royce 89.49 71.98 63.61 74.96 61.16
Lucille Roybal-Allard 73.64 54.58 93.5 65.22 74.25
Kevin McCarthy 71.28 66.23 58.92 83.22 78.13
Jackie Speier 82.85 59.65 66.78 50.04 98.21
Adam Schiff 82.29 73.24 60.37 67.96 72.25
Anna Eshoo 59.12 92.06 54.39 64.6 85.05
Ami Bera 65.09 55.25 73.38 99.05 59.08
Julia Brownley 54.7 50.72 70.13 93.5 82.01
Ken Calvert 68.94 76.28 70.85 64.08 68.66
Barbara Lee 58.47 79.48 56.16 95.09 57.87
Tony Cardenas 99.86 52.14 69.72 71.18 52.36
Mimi Walters 85.5 67.32 54.38 68.05 69.33
Linda Sanchez 65.15 52.96 92.11 51.61 79.65
Jimmy Panetta 62.86 66.83 69.74 72.33 65.58
Jimmy Gomez 60.11 94.61 63.18 55.07 56.89
Pete Aguilar 66.96 68.56 61.09 54.29 73.53

1 个答案:

答案 0 :(得分:2)

outputTxt(sortByFirstName(members), sortByApprovalRating(members));

您的排序方法正在对传递的数组进行排序,而不是创建新的数组。因为在输入outputTxt之前调用了这两种排序,所以最终会按批准率对数组进行排序。

您可以通过以下方式更改排序方法:

// Returns array of congress member objects sorted alphabetically by first
// name
public static CongressMembers[] sortByFirstName(CongressMembers[] inarray) {
    CongressMembers temp;
    CongressMembers[] array = new CongressMembers[inarray.length];
    System.arraycopy(inarray, 0, array, 0, array.length);
    for (int i = 0; i < array.length - 1; i++) {
        for (int j = 0; j < array.length - i - 1; j++) {
            if (array[j + 1].getName().compareTo(array[j].getName()) < 0) {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }
    return array;

}

// Returns array of congress member objects by average approval rating
// (highest to lowest)
public static CongressMembers[] sortByApprovalRating(CongressMembers[] inarray) {
    CongressMembers temp;
    CongressMembers[] array = new CongressMembers[inarray.length];
    System.arraycopy(inarray, 0, array, 0, array.length);
    for (int i = 0; i < array.length - 1; i++) {
        for (int j = 0; j < array.length - i - 1; j++) {
            if (array[j + 1].getAvgApprovalRating() > array[j].getAvgApprovalRating()) {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }
    return array;

}

这应该可以解决您的问题。下一步是提高效率; - ):

// Returns array of congress member objects sorted alphabetically by first
// name
public static CongressMembers[] sortByFirstName(CongressMembers[] inarray) {
    CongressMembers[] array = new CongressMembers[inarray.length];
    System.arraycopy(inarray, 0, array, 0, array.length);
    Arrays.sort(array, (elem1, elem2) -> {
        return String.CASE_INSENSITIVE_ORDER.compare(elem1.getName(), elem2.getName());
    });
    return array;
}

// Returns array of congress member objects by average approval rating
// (highest to lowest)
public static CongressMembers[] sortByApprovalRating(CongressMembers[] inarray) {
    CongressMembers[] array = new CongressMembers[inarray.length];
    System.arraycopy(inarray, 0, array, 0, array.length);
    Arrays.sort(array, (elem1, elem2) -> {
        Integer.compare(elem1.getAvgApprovalRating(), elem2.getAvgApprovalRating());
    });
    return array;
}

这使得按名称排序不区分BTW。