3 回答

TA貢獻1831條經驗 獲得超9個贊
public enum Grade {
A("A", 95, 100),
AMINUS("A-", 92, 94),
BPLUS("B+", 89, 91),
B("B", 86, 88),
BMINUS("B-", 83, 85),
CPLUS("C+", 80, 82),
C("C", 77, 79),
CMINUS("C-", 74, 76),
DPLUS("D+", 71, 73),
D("D", 68, 70),
DMINUS("D-", 65, 67),
F("F", 1, 64),
FA("FAILURE TO APPEAR", 0, 0);
private final String text;
private final int min;
private final int max;
Grade(String text, int min, int maxScore) {
this.text = text;
this.min = min;
this.max = maxScore;
}
public String getText() {
return text;
}
public static Grade parseScore(int score) {
for (Grade grade : values())
if (score >= grade.min && score <= grade.max)
return grade;
throw new EnumConstantNotPresentException(Grade.class, String.valueOf(score));
}
}
現在您可以將分數轉換為Gradle:
Grade grade = Grade.parseScore(85); // BMINUS

TA貢獻1783條經驗 獲得超4個贊
您需要將邊界定義為單獨的字段,以便編譯器理解??赡苣趯ふ疫@樣的枚舉:
public enum Grade {
A("A", 95, 100),
AMINUS("A-", 92, 94);
// DEFINE ALL YOUR GRADES HERE
String grade;
int gradeMin;
int gradeMax;
Grade(String grade, int gradeMin, int gradeMax) {
this.grade = grade;
this.gradeMin = gradeMin;
this.gradeMax = gradeMax;
}
/**
* @return the grade
*/
public String getGrade() {
return grade;
}
/**
* @return the gradeMin
*/
public int getGradeMin() {
return gradeMin;
}
/**
* @return the gradeMax
*/
public int getGradeMax() {
return gradeMax;
}
public static Grade getGrade(int marks) {
for (Grade g : values()) {
if (marks >= g.getGradeMin() && marks <= g.getGradeMax()) {
return g;
}
}
return null;
}
}
然后你可以在你的課堂上使用它來獲得成績
public class GradeRetriever {
public static void main(String... args) {
System.out.println(Grade.getGrade(92).getGrade());
}
}

TA貢獻1942條經驗 獲得超3個贊
構造函數不會按照您使用它的方式工作。如果您想將值添加到枚舉類型,就像您在此處所做的那樣,您需要在構造函數中設置這些值。
因此,枚舉類型只需要一個構造函數,并且構造函數永遠不能被另一個 java 類使用。
由于 Java 中沒有簡單的范圍類,我建議您將最小值和最大值定義為單獨的參數:
public enum Grade {
A(95, 100, "A")
// and so on
String gradeText;
int gradeMinPoints;
int gradeMaxPoints;
// ...
}
在您的構造函數中,您需要分配這些值:
private Grade (int minimum, int maximum, String text) {
this.gradeMinPoints = minimum;
this.gradeMaxPoints = maximum;
this.gradeText = text;
}
您可以通過其他函數訪問變量,并根據您提供的參數聲明返回“等級”枚舉類型的靜態函數。這篇文章的其他答案提供的功能比我寫的要好得多,所以我會向你推薦那些。
添加回答
舉報