我是Java的新手并且正在学习它。所以这可能是我的超级愚蠢问题。假设我有TaskCanceledException
这样的课程:
enum
如果不在public class Diamant implements Comparable<Diamant> {
final private String stockNr;
final private double karaat;
final private String helderheid;
final private char kleur;
final private String snede;
public Diamant(String stockNr, double karaat, String helderheid, char kleur, String cut) {
this.stockNr = stockNr;
this.karaat = karaat;
this.helderheid = helderheid;
this.kleur = kleur;
this.snede = cut;
}
public String getStockNummer() {
return stockNr;
}
public double getKaraat() {
return karaat;
}
public String getHelderheid() {
return helderheid;
}
public char getKleur() {
return kleur;
}
public String getSnede() {
return snede;
}
enum Color {
D(0), E(1), F(2), G(3), H(4), I(5), J(6), K(7), L(8), M(9), N(10), O(11),
P(12), Q(13), R(14), S(15), T(16), U(17), V(18), W(19), X(20), Y(21), Z(22);
int quality;
Color(int quality) {
this.quality = quality;
}
public int getQuality() {
return quality;
}
}
enum Brightness {
FL(0), IF(1), VVS1(2), VVS2(3), VS1(4), VS2(5), SI1(6), SI2(7), I1(8), I2(9), I3(10);
int quality;
Brightness(int quality) {
this.quality = quality;
}
public int getQuality() {
return quality;
}
}
@Override
public String toString() {
return "StockNr='" + getStockNummer() + "\t" +
" Karaat=" + getKaraat() + "\t" +
" Helderheid='" + getHelderheid() + "\t" +
" Kleur=" + getKleur() + "\t";
}
@Override
public int compareTo(Diamant other) {
//Sort according to Karaat (Max=5.0)
if (this.getKaraat() < other.getKaraat()) {
return 1;
} else if (this.getKaraat() > other.getKaraat()) {
return -1;
} else {
// Sort according to Kleur first then Helderheid
Color.D.getQuality();
(this.getKleur()).getQuality();
if (this.getKleur() < other.getKleur()) {
return 1;
} else if (this.getKleur() > other.getKleur()) {
return -1;
} else {
return 0;
}
}
}
中明确键入getQuality
值,如何使用方法enum
。换句话说,这很好用:
CompareTo
但是,这不起作用(尽管方法Color.D.getQuality();
会返回getKleur
):
D
如果不用硬键入字母,我如何使用Color.(this.getKleur()).getQuality();
方法enum
?
答案 0 :(得分:3)
这应该可以正常工作:
class YourClass {
Color getColor() { return Color.D; }
...
YourClass thingy = new YourClass(...
System.out.println(thingy.getColor().getQuality());
说明:Color
是有效的返回类型;并且定义为返回Color
的方法可以返回该Enum的任何实例。然后可以使用它......好吧,正如您所期望的那样。
鉴于你的意见:
final private char kleur;
显然&#34;错误&#34;。枚举的要点是...成为枚举。所有枚举常量都是单个字符的事实并不神奇地制作
char klear = D;
有效的作业。因此,显而易见的答案是将代码更改为
final private Color kleur;
请注意:如果您需要&#34;字符串化&#34;表示,你可以随时做
Color whatever = Color.D;
System.out.println(whatever.name());
例如(以上将打印&#34; D&#34;)。
答案 1 :(得分:1)
试试这个:
Color.valueOf(String.valueOf(this.getKleur())).getQuality();
答案 2 :(得分:0)
this.getKleur()返回一个字符,而不是Color enum的实例,这就是Color。(this.getKleur())。getQuality();不起作用。 你需要在这里采取一种迂回的方法:
Color.valueOf(Character.toString(this.getKleur())).getQuality();