当没有要打印的代码时,为什么要打印方法

时间:2018-02-07 09:23:41

标签: java oop exception-handling

尝试在最后的第二部分获得此输出:

/*****test finalistsToFile2 with sorted arraylist*****/

/**************check file testSorted.txt**************/

/****************************************************/

但是,我的实际输出是:

/****************************************************/

/*****test finalistsToFile2 with sorted arraylist*****/

/**************check file testSorted.txt**************/

**ID: 85011, Final Mark: 69.2, Classification: UPPER_SECOND
Candidate is BORDERLINE
ID: 62138, Final Mark: 59.9, Classification: LOWER_SECOND
Candidate is BORDERLINE**

/****************************************************/

我尝试过调试,但仍然找不到“检查文件testSorted.txt”(粗体)下额外4行打印的根本原因。知道我能做什么吗?我总共使用了3个类,如下所示:

ProcessDegreeMark类

import java.util.*;
import java.io.*;

public class ProcessDegreeMark{

private ProcessDegreeMark() {}

public static ArrayList<Finalist> finalistsInList(String s) throws Exception{
    ArrayList<Finalist> finalists = new ArrayList<Finalist>();
    String id;
    double mark;
    Scanner in = null;
    try
    {
        in = new Scanner(new FileReader(s));
        try
        {
            while(in.hasNextLine())
            {
                id =in.nextLine();
                mark = Double.parseDouble(in.nextLine());
                finalists.add(new Finalist(id,mark));
            }
        }
        finally
        {
            in.close();
        }
    }
    catch(IOException e)
    {
        System.out.println(s+" not found");
    }
    return finalists;
 }


public static void displayFinalists(ArrayList<Finalist> finalists){
  for (int i = 0; i < finalists.size(); i++)
  {
       System.out.println(finalists.get(i));
  }
}


public static void findFinalistID(ArrayList<Finalist> a, String s){
    int count =0;
    for (int i=1;i<a.size();i++)
    {
        if (((a.get(i))).getId().equals(s))
        {
            System.out.println(a.get(i));
            count++;
        }
    }
    if(count==0)
    {
        System.out.println("No candidate found with ID number "+s);
    }
}

public static void findFinalistClass(ArrayList<Finalist> a, String s){
    int count =0;
    for (int i=1;i<a.size();i++)
    {
        if (((a.get(i))).getdegreeClass().equals(s))
        {
            System.out.println(a.get(i));
            count++;
        }
    }
    if(count==0)
    {
        System.out.println("No candidate found with degree class "+s);
    }
}

public static ArrayList<Finalist> sortDegreeMark(ArrayList<Finalist> a){
    ArrayList<Finalist> sortedFinalists = new ArrayList<Finalist>();
    sortedFinalists.addAll(a);
    Collections.sort(sortedFinalists, new FinalistComparator());
    return sortedFinalists;


}

public static void finalistsToFile2(ArrayList<Finalist> finalists, String s) {
    try
    {
        PrintStream out = new PrintStream(new FileOutputStream(s));
        try
        {
            for(int i = 0; i < finalists.size(); i++)
            {
                out.println(finalists.get(i));
            }
        }
        finally
        {
            out.close();
        }
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }

}

public static void findAndSaveFinalistClass(ArrayList<Finalist> a, String s){
    ArrayList<Finalist> searchFinalists = new ArrayList<Finalist>();
    int count =0;
    for (int i=1;i<a.size();i++)
    {
        if (((a.get(i))).getdegreeClass().equals(s))
        {
            System.out.println(a.get(i));
            searchFinalists.add(a.get(i));
            finalistsToFile2(searchFinalists,"testSorted.txt");
            count++;
        }
    }
    if(count==0)
    {
        System.out.println("No candidate found with degree class "+s);
    }
}

    public static void main(String[] args) throws Exception{
 System.out.println("/****************************************************/");
         System.out.println("/*******finalistsInList with invalid file name*******/");
         System.out.println();
         ArrayList<Finalist> testList = finalistsInList("file***.txt");
         System.out.println();
         System.out.println("/****************************************************/");
         System.out.println("/********finalistsInList with valid file name********/");
         System.out.println("/********display to check arraylist populated********/");
         System.out.println();
         ArrayList<Finalist> finalists = finalistsInList("finalMark.txt");
         displayFinalists(finalists);
         System.out.println();
         System.out.println("/****************************************************/");
         System.out.println("/*testing findFinalistID with valid and invalid data*/");
         System.out.println();
         findFinalistID(finalists, "75021");  
         findFinalistID(finalists, "21050");
         System.out.println();
         System.out.println("/****************************************************/");
         System.out.println("/*test findFinalistClass with valid and invalid data*/");
         System.out.println();
         findFinalistClass(finalists, "FIRST"); 
         findFinalistClass(finalists, "THIRD"); 
         System.out.println();
         System.out.println("/****************************************************/");
         System.out.println("/*****run sortedFinalists then test with display*****/");
         System.out.println();
         ArrayList<Finalist> sortedFinalists = sortDegreeMark(finalists);
         displayFinalists(sortedFinalists);
         System.out.println();
         System.out.println("/****************************************************/");
         System.out.println("/*****test finalistsToFile2 with sorted arraylist*****/");
         System.out.println("/**************check file testSorted.txt**************/");
         System.out.println();
         finalistsToFile2(sortedFinalists, "testSorted.txt"); //save the sorted arraylist to a new file, check by opening file
         System.out.println();
         System.out.println("/****************************************************/");
         System.out.println("/*test findAndSaveFinalistClass with valid and invalid data*/");
         System.out.println();
         findAndSaveFinalistClass(finalists, "FIRST"); //test method finds
         findAndSaveFinalistClass(finalists, "THRID"); //check appropriate error message when nothing found, open new text file
         System.out.println();
         System.out.println("/*********************THE END************************/");
     }
}

入围级

public class Finalist{

private String id;
private double degreeMark;
private String degreeClass;
private boolean borderline;


public Finalist(String id, double degreeMark) {
    this.id = id;
    this.degreeMark = degreeMark;
    borderline = calcBorderline();
    degreeClass = assignDegreeClass();
}

private String assignDegreeClass(){//change method name
    if (degreeMark<40) return "FAIL";
    if (degreeMark<50) return "THIRD";
    if (degreeMark<60) return "LOWER_SECOND";
    if (degreeMark<70) return "UPPER_SECOND";
    return "FIRST";
}

 private boolean calcBorderline(){
     double x;
     if (degreeMark<40){
         x = 40.0-degreeMark;
         if (x < 1.0) return true;
     }
     if (degreeMark<50){
         x = 50.0-degreeMark;
         if (x < 1.0) return true;
     }
     if (degreeMark<60){
         x = 60.0-degreeMark;
         if (x < 1.0) return true;
     }
     if (degreeMark<70){
         x = 70.0-degreeMark;
         if (x < 1.0) return true;
     }
     return false;
}

public String getId(){
    return id;
}

public double getDegreeMark(){
    return degreeMark;          
}

public String getdegreeClass(){
    return degreeClass;
}

public boolean getborderline(){
    return borderline;
}

 public String toString() {
    String s = "ID: " + id + ", Final Mark: " + degreeMark + ", Classification: " + degreeClass + System.lineSeparator();
    if(calcBorderline()==true)
    {
        System.out.print(s);
        System.out.println("Candidate is BORDERLINE");
    }
    else if(calcBorderline()==false)
    {
        return s;
    }
    return "";

}
}

FinalistComparator类

import java.util.Comparator;

//sort by degree mark, descending

class FinalistComparator implements Comparator<Finalist> {
@Override
public int compare(Finalist f1, Finalist f2) {
    int degreeComparisonResult = Double.compare(f2.getDegreeMark(),f1.getDegreeMark());
        return degreeComparisonResult;
}
}

1 个答案:

答案 0 :(得分:0)

由于Finalist.toString(),意外输出在out.println(finalists.get(i));中执行。由于PrintStream.println(Object x)调用了所提供对象的toString()

更新,因为您声明需要第二行:Candidate is BORDERLINE只需将其添加到返回值,不要直接在System.out上打印,否则您将获得意想不到的输出。

@Override
public String toString() {
    String s = "ID: " + id + ", Final Mark: " + degreeMark + ", Classification: " + degreeClass + System.lineSeparator();
    if(calcBorderline()) {
        s += "Candidate is BORDERLINE" + System.lineSeparator();
    }
    return s;
}

原始回答:

因此,请避免在System.out.println()中使用toString(),我建议尽量保持简单,并将逻辑放在另一种方法中。
例如:

public class Finalist{
    /* all the other code */

    @Override
    public String toString() {
        return "ID: " + id + ", Final Mark: " + degreeMark + ", Classification: " + degreeClass;
    }
}

public class ProcessDegreeMark {
    /** Writes all non BORDERLINE candidates in the file and outputs the skipped finalists to System.out */
    public static void saveToFileWithoutBorderline(List<Finalist> list, File file) {
        try (PrintStream out = new PrintStream(new FileOutputStream(file))){
            for(Finalist finalist : list) {
                if(finalist.calcBorderline()) {
                    System.out.println("Skip BORDERLINE candidate: "+finalist.toString());
                } else {
                    out.println(finalist.toString());
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

我只提供了一个示例代码来跳过saveToFile中的边界候选者,因为我不知道你必须跳过或禁止它们。