简体   繁体   English

PrintWriter方法中的奇怪错误

[英]Strange Error in PrintWriter method

Main summary of code function pertaining to my problem: The code takes an array of congress members and sorts them in two different methods; 与我的问题有关的代码功能的主要摘要:该代码采用一组会议成员并将其按两种不同的方法进行排序; one sorts by first name, one sorts by average approval rating. 一个按名字排序,一个按平均批准等级排序。 The code then outputs the two newly sorted arrays into a txt file. 然后,代码将两个新排序的数组输出到txt文件中。

The problem I am dealing with is an error I can't seem to trace. 我正在处理的问题是我似乎无法跟踪的错误。 In my main class, I am outputting the data in the void outputTxt method, and it seems that when I am first trying to output the array sorted alphabetically, it outputs the array sorted numerically, even though I call them separately in the parameters. 在我的主类中,我以void outputTxt方法输出数据,似乎当我第一次尝试输出按字母顺序排序的数组时,即使我在参数中分别调用它们,它也会输出按数字顺序排序的数组。 Tried tracing through everything and I am completely lost as to how this is happening. 试图跟踪所有内容,我完全不知道这是如何发生的。

Main Class (imports accidentally withheld, no big deal): 主舱(进口货物意外扣留,没什么大不了的):

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();
}

} }

Congress Member Object: 国会议员对象:

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 file (note: average approval rating sort puts Mark DeSaulnier at the top and Pete Aguilar at the bottom, so the only problem I'm facing is with the first list...it's sorted by average approval rating and not by first 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
outputTxt(sortByFirstName(members), sortByApprovalRating(members));

Your sorting methods are sorting the passed array instead of creating a new one. 您的排序方法是对传递的数组进行排序,而不是创建一个新数组。 Because both sorts are called before you enter outputTxt you end up with the array being sorted by approval rates. 由于在输入outputTxt之前都会调用这两种排序,因此最终会按批准率对数组进行排序。

You can change your sorting method this way: 您可以通过以下方式更改排序方式:

// 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;

}

This should solve your problem. 这应该可以解决您的问题。 Next step is making it more efficient ;-): 下一步是提高效率;-):

// 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;
}

This makes the sorting by name case insensitive BTW. 这使得按名称排序不区分大小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM