Reputation: 159
Good day people, I have an assignment to write a Java enumeration that represents letter grades A through F.
That if all good, with the following code that I use:
A(true), B(true), C(true), D(true), E(true), F(false);
The Boolean value indicates whether the student has passed or failed.
The problem is that we need to include plus and minus grades. But I don't know how to structure it...A+ etc. doesn't work.
Any advice or help will be much appreciated.
Upvotes: 1
Views: 2347
Reputation: 267
well try to used the class like below Note: this is the easy way to access the grade.
public class Grade {
private Long id;
// this will be the upper case store and read
private String grade;
}
Upvotes: 0
Reputation: 20266
You will use the enum pattern. It works also with the plain class, the Java enum is just a syntactic sugar.
First the class solution, so you may compare it.
public class Grade {
final public static Grade A = new Grade(true, "A");
final public static Grade A_PLUS = new Grade(true, "A+");
final public static Grade A_MINUS = new Grade(true, "A-");
...
final public static Grade E = new Grade(true, "E");
final public static Grade F = new Grade(false, "F");
final private boolean passed;
final private String name;
// private constructor - no-one can create any other instance then those above
private Grade(boolean passed, String name) {
this.passed = passed;
this.name = name;
}
public boolean hasPassed() {
return this.passed;
}
@Override
public String toString() {
return this.name;
}
}
Then for comparison the enum solution. You should understand the design pattern. Enum is just more convenient syntax + more reliable serializability, nothing more.
public enum Grade {
A(true),
A_PLUS(true),
A_MINUS(true),
B(true),
B_PLUS(true),
...
E(true),
F(false);
final private boolean passed;
private Grade(boolean passed) {
this.passed = passed;
}
public boolean hasPassed() {
return this.passed;
}
// Thanks to special bonus functionality of enums, which are aware of their name
@Override
public String toString() {
final String name = name();
if (name.contains("PLUS")) {
return name.charAt(0) + "+";
}
else if (name.contains("MINUS")) {
return name.charAt(0) + "-";
}
else {
return name;
}
}
}
Upvotes: 0
Reputation: 13566
As Kocko, answered, you cannot use A+
as +
is an operator in java but you can override toString()
method so that you can give some meaningful representation to enum type.
If you want you could use a string representation like A+
for enum A_PLUS
using toString
method. Learn more about enumeration in java
Upvotes: 0
Reputation: 62864
А+
doesn't work, because the +
is an operator in Java.
Better add a few more grades, like:
A_PLUS(true), A_MINUS(true), .... , F_PLUS(false);
Upvotes: 3