首先,我的代码(远非完美,我真的不知道自己在做什么)是这样的:
public enum Chord { MAJOR, MINOR, DIMINISHED, BASS, BASS2 }
public enum Scales { C, D, E, F, G, A }
public class EnumTest
{
Chord chord;
public EnumTest(Chord chord)
{
this.chord = chord;
}
public void tellItLikeItIs()
{
switch (chord) {
case MAJOR:
for(Scales C : Scales.values())
System.out.println(C + " " + C.ordinal());
break;
//I've tried in the CHORD enum going MAJOR(0, 2, 4) but I don't think that was correct
case MINOR: System.out.println("C, Eb, G");
break;
default:
System.out.println("I screwed up");
break;
}
}
public static void main(String[] args)
{
EnumTest firstDay = new EnumTest(Chord.MAJOR);
firstDay.tellItLikeItIs();
EnumTest thirdDay = new EnumTest(Chord.MINOR);
thirdDay.tellItLikeItIs();
System.out.println("Here are all Scale degrees" +
" and their ordinal values: ");
for(Scales C : Scales.values())
System.out.println(C + " " + C.ordinal());
}
}
我可能缺少一些括号和其他内容,使用代码工具发布某些内容时遇到了麻烦。我的问题是,对于MAJOR,我可以让编译器打印C 0,D 1,E 2等。但是我只希望它打印C,E和G(0、2、4)。有没有办法为大和弦仅选择这3个序数值并将其打印出来?
另外,在Scales枚举中,我还需要使用尖锐字符(C,C#,D,D#..),但是尖锐字符是“非法字符”,并且我得到
_MusicChord\Scales.java:2: illegal character: \35
我试图查看转义字符,但我要么没有了解我读过的文章,或者我看错了什么。有人可以告诉我如何将#添加到Scales类中,而不让它们成为非法字符吗?任何帮助表示赞赏 最佳答案
在以下示例中,您可以看到如何解决所面临的一些问题:
public class EnumTest
{
public enum Chord
{
MAJOR,
MINOR,
DIMINISHED,
BASS,
BASS2
}
public enum Scales
{
C("C"),
CSharp("C#"),
E("E"),
F("F"),
G("G"),
A("A");
private final String printName;
Scales(String printName)
{
this.printName = printName;
}
public String getPrintName()
{
return printName;
}
public String toString()
{
return printName;
}
private static final Map<Chord, List<Scales>> scalesForChord;
static
{
scalesForChord = new HashMap<Chord, List<Scales>>();
scalesForChord.put(Chord.MAJOR, Arrays.asList(Scales.C, Scales.E, Scales.G));
}
public static List<Scales> getScalesForChord(Chord chord)
{
return scalesForChord.get(chord);
}
}
}