tags:

views:

118

answers:

3

When I enter a string that it not in the list, I get this error in my enum CrimeType

class: IllegalArgumentException, no enum const class CrimeType.a(in java.lang.Enum).

What does it mean and how can I fix this?

public void enterCrime()
{
    Crimes crimes = new Crimes();
    System.out.print("\t\tEnter crime: ");
    crimeName = In.nextLine();

    if("murder".equals(crimeName) || "arson".equals(crimeName) || "assault".equals(crimeName))
    {            
        crimes.daysToStay(3);        
    }
    else if("fraud".equals(crimeName) || "theft".equals(crimeName) || "vandalism".equals(crimeName))
    {
        crimes.daysToStay(2);
    }
    else if("drunk".equals(crimeName) || "littering".equals(crimeName) || "badHair".equals(crimeName))
    {
        crimes.daysToStay(1);
    }
    else
    {
        System.out.println("\t\tThat is not a valid crime. The crimes are");
        crimes.list();
    }      
    crimes.add(crimeName);
    enterAction();  
}

Enum Class

public enum CrimeType
{
    murder, arson, assault, fraud, theft, vandalism, drunk, littering, badHair;
}

Crimes Class

import java.util.*;
import java.text.*;
public class Crimes
{
    private LinkedList<CrimeType> crimes = new LinkedList<CrimeType>();    

    public Crimes()
    {       
    }

    public void add(String crime)
    {
        CrimeType newCrime = CrimeType.valueOf(crime);
        crimes.add(newCrime);
    }

Ok, i've changed it to .equals now, which fixes the first problem, but when I enter something else, I still get that error in the enum class.

+3  A: 

You should be using the equals() method to compare strings, instead of ==.

e.g.

"murder".equals(crimeName)
dogbane
+4  A: 

crimes.add() is executing regardless of whether there is a valid crime or not. This is most likely the method that is throwing the exception (although we can't know without knowing the data type of crimes). Presumably that method casts the crime string to an enum using an invalid string.

Martin Doms
I think Martin is right. I'm pretty sure you shouldn't call crimes.add() for an invalid crime. You'll end up calling CrimeType.valueOf(crime) for a string not defined in the enum. Your enterCrime() method needs to be re-worked slightly. Once an invalid crime is detected it should stop processing.
dave
+3  A: 

Check the API-Docs for Enum.valueOf. I guess that's where you will find an explanation for your problem: "... IllegalArgumentException - if the specified enum type has no constant with the specified name, or the specified class object does not represent an enum type ..."

zlajo