I'm currently coding a Minecraft Mod in Java and I have some issues about implementing the Exception correctly.
I tried in the Class below different things:
- Before I used Maps instead of List
- using Try and Catch Method
- For Loop to get the ID
What I wanted is if you use the register Method and any of one of the If Statements goes true it throwing an Exception but it doesn't at all. It's like the if statements are always false.
Here is the Class:
public class SoulType {
private static final List<SoulType> SOUL_TYPES = new ArrayList<>();
private final String id;
private final String displayName;
private final SoulTypeRarities rarity;
private final double corruption;
private double strength;
private SoulType(String id, String displayName, SoulTypeRarities rarity, double corruption, double strength) {
this.id = id;
this.displayName = displayName;
this.rarity = rarity;
this.corruption = corruption;
this.strength = strength;
}
public static List<SoulType> getSoulTypes() { // Neue Getter-Methode
return SOUL_TYPES;
}
public String getId() {
return id;
}
public String getDisplayName() {
return displayName;
}
public SoulTypeRarities getRarity() {
return rarity;
}
public Double getCorruption() {
return corruption;
}
public Double getStrength() {
return strength;
}
public void setStrength(double newStrength) {
this.strength = newStrength;
}
public void addStrength(double addStrength) {
this.strength += addStrength;
}
public static SoulType register(String id, String displayName, SoulTypeRarities rarity, double corruption, double strength) throws IllegalArgumentException {
double minCorruption = 0;
double maxCorruption = 2;
double minStrength = 0;
double maxStrength = 5;
if (corruption < minCorruption || corruption > maxCorruption) {
throw new IllegalArgumentException("Corruption must be between " + minCorruption + " and " + maxCorruption + " .");
}
if (strength < minStrength || strength > maxStrength) {
throw new IllegalArgumentException("Strength must be between " + minStrength + " and " + maxStrength + " .");
}
SoulType newType = new SoulType(id, displayName, rarity, corruption, strength);
SOUL_TYPES.add(newType);
for (SoulType soulType : SOUL_TYPES) {
if (soulType.getId().equals(id)) {
throw new IllegalArgumentException("SoulType with id '" + id + "' already exists.");
}
}
return newType;
}
public static SoulType fromId(String id) {
for (SoulType soulType : SOUL_TYPES) {
if (soulType.getId().equals(id)) {
return soulType;
}
}
throw new IllegalArgumentException("SoulType with id '" + id + "' not found.");
}
}
Also here is the Class where the Method is called:
public class SoulTypes {
public static final SoulType HARMONY = SoulType.register("harmony", "Harmonie", SoulTypeRarities.COMMON, 0.0, 1.0);
public static final SoulType BOLLWERK = SoulType.register("bollwerk", "Bollwerk", SoulTypeRarities.RARE, 0.8, 1.5);
}
I hope someone can help me out of this Issue.