Results 1 to 4 of 4
  1. #1
    Scopic is offline Member
    Join Date
    Oct 2011
    Posts
    24
    Rep Power
    0

    Default Strange error in my code, unsure what it is referring to.

    ****WARNING: LONG POST!****

    Hi all,

    I am having an issue with my code. It's a little difficult to explain so I'll show you the code first and then I'll give an example of what's happening:

    Hopefully this is all the relevant code you need:

    MAIN

    Java Code:
    package assignment.pkg2;
    
    import java.util.Scanner;
    
    public class Assignment2 {
        
        //Function for user menu display and input
        public static int getMenuChoice()
            {
                Scanner keyboard = new Scanner(System.in);
                
                System.out.println("\n-----------------------------"
                + "\nHere are your Choices: \n"
                + "Enter 1 to add a Subscriber \n"
                + "Enter 2 to add an Application \n"
                + "Enter 3 to flag a Subscriber \n"
                + "Enter 4 to flag an Application \n"
                + "Enter 5 to unflag a Subscriber \n"
                + "Enter 6 to unflag and Application \n"
                + "Enter 7 to display all Subscribers \n"
                + "Enter 8 to display all Applications \n"
                + "Enter 9 to Quit "
                        + "\n-----------------------------\n");
                
                return keyboard.nextInt();
            }
        
        public static void main(String[] args) {
            
            //Field declarations
            ElementSet set = new ElementSet();
            Element anElement;
            Subscriber aSub;
            Application anApp;
    
            Scanner keyboard = new Scanner(System.in);
            
            int menuChoice;
            
            String anyMoreSub;
            String anyMoreApps;
            String subSearch;
            String appSearch;
            
            boolean isDone = false;
    
            menuChoice = getMenuChoice();
    
            //Initiate loop to display menu
            while(!isDone)
            {
                 if(menuChoice == 9)
                {
                    System.out.println("Are you sure you want to quit? (Y/N)");
                    String askQuit;
                    askQuit = keyboard.nextLine().toUpperCase();
                    
                    if(askQuit.equals("Y"))
                    {
                        isDone = true;
                        break;
                    }
                }
            
                switch(menuChoice)
                {
                    
                case 1:
                    //add subscriber to Element Set array
                    anElement = new Subscriber();
                    anElement.readIn();
                    set.add(anElement);
                break;
                
                case 2:
                    //add application to Element Set array
                    anElement = new Application();
                    anElement.readIn();
                    set.add(anElement);         
                break;
                
                case 3:
                    //flag a specified subscriber
                    System.out.println("Enter Subscriber's name: ");
                    subSearch = keyboard.nextLine().toUpperCase();
    
                    for(int i = 0; i < set.size(); i++)
                    {
                        anElement = set.getCurrent();
    
                        aSub = (Subscriber) anElement;
                            if((aSub.getName()).equals(subSearch))
                            {
                                set.flagIt(aSub);
                            }
                            else
                            {
                                System.out.println("Member not found.");
                            }
                    }
                    
                break;
                
                case 4:
                    //flag a specified application
                    System.out.println("Enter Application's name: ");
                    subSearch = keyboard.nextLine().toUpperCase();
                    for(int i = 0; i < set.size(); i++)
                    {
                        anElement = set.getCurrent();
    
                            anApp = (Application) anElement;
                            if((anApp.getName()).equals(subSearch))
                            {
                                
                                set.flagIt(anApp);
                            }
                            else
                            {
                                System.out.println("Member not found.");
                            }
                    }
                    
                break;
                
                case 5:
                    //unflag a specified subscriber
                    System.out.println("Enter Subscriber's name: ");
                    subSearch = keyboard.nextLine().toUpperCase();
    
                    for(int i = 0; i < set.size(); i++)
                    {
                        anElement = set.getCurrent();
    
                        aSub = (Subscriber) anElement;
                            if((aSub.getName()).equals(subSearch))
                            {
                                set.unFlagIt(aSub);
                            }
                            else
                            {
                                System.out.println("Member not found.");
                            }
                    }
                break;
                
                case 6:
                    //unflag a specified application
                    System.out.println("Enter Application's name: ");
                    subSearch = keyboard.nextLine().toUpperCase();
    
                    for(int i = 0; i < set.size(); i++)
                    {
                        anElement = set.getCurrent();
    
                            anApp = (Application) anElement;
                            if((anApp.getName()).equals(subSearch))
                            {
                                set.unFlagIt(anApp);
                            }
                            else
                            {
                                System.out.println("Member not found.");
                            }
                    }
                break;
                
                case 7:
                    //display all Subscribers in the Element Set array
                    set.displayAllInClass(Subscriber.class.getName());
                break;
                
                case 8:
                    //display all Applications in the Element Set array
                    set.displayAllInClass(Application.class.getName());
                break;
                
                    
                }
                
                menuChoice = getMenuChoice();
                
            } 
    
        }  
    
    }
    ELEMENTSET CLASS

    Java Code:
    package assignment.pkg2;
    
    
    public class ElementSet {
        
        //Field declarations
        private Element[] elementList;
        
        private boolean[] flagged;
        
        private int currentIndex;
        private int currentSize;
        
        private final int MAXSETSIZE = 100;
        
        //Default Constructor
        public ElementSet()
        {
            elementList = new Element[MAXSETSIZE];
            flagged = new boolean[MAXSETSIZE];
            
            for(int i = 0; i < MAXSETSIZE; i++)
            {
                flagged[i] = false;
            }
      
            currentIndex = -1;
            currentSize = 0;
        }
        
        //Declare isMemberOf function
        public boolean isMemberOf(Element anElement)
        {
            String paramClass = anElement.getClassName();
            String currClass;
            
            for (int i = 0; i < currentSize; i++)
            {
                currClass = elementList[i].getClassName();
                
                if (currClass.equals(paramClass))
                {
                    if (elementList[i].equals(anElement))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        
        //Check if array is full
        public boolean isFull()
        {
             return currentSize == MAXSETSIZE;
        }
        
        //Check if array is empty
        public boolean isEmpty()
        {
             return currentSize == 0;
        }
        
        //Check current size of array
        public int size()
        {
             return currentSize;
        }
        
        //Declare getCurrent method
        public Element getCurrent()
        {
             // Local data ...
             int saveIndex = currentIndex;
           	
          	// Logic ...
             if (currentIndex == currentSize - 1)
             {
                // Recycle to beginning of list
                currentIndex = 0;
             }
             else
             {
                // Advance currentIndex to next object
                currentIndex++;
             }
             
          	// Return a reference to a clone of the current object
             return elementList[saveIndex].clone(); 
        }
        
        //Declare add method
        public int add(Element anElement)
        {
              // Logic ...
             if (currentSize == MAXSETSIZE)
             {
                 System.out.println("Set is full, member not added.");
                return 0;  // set is full
             }
             else if (this.isMemberOf(anElement))
             {
                 System.out.println("Member is already in the set.");
                return -1; // it's already in there
             }
           
             // We will add a clone of anElement to
          	// the set.
             elementList[currentSize] = anElement.clone();
           
             // Increment currentSize.
             currentSize++;
          
             // Set currentIndex to object we just added if it was the
             // first object in the set. 
             if (currentSize == 1) currentIndex = 0;
          
             // We succeeded.
             return 1;
        }
        
        //Declare clear method
        public void clear()
          {
           	// Clean up the memory associated with this object 
          	// while it is still in use.
             for (int i = 0; i < currentSize; i++)
             {
                elementList[i] = null;
             }
             
          	// Reset currentSize and currentIndex to empty set 
          	// values.
             currentIndex = -1;
             currentSize = 0;
          }
      
         //Declare display method   
         public void display()
          {
             if (currentSize == 0)
             {
                System.out.println("There are no objects in the set. ");
             }
             else 
             {
                System.out.println("Here are the objects in the set: \n");
                for (int i = 0; i < currentSize; i++)
                {
                   elementList[i].display();
                   System.out.println("\n");
                }
             }
          
          }
      
        //Declare flagIt method
        public int flagIt(Element anElement)
        {
            String paramClass = anElement.getClassName();
            String currClass;
            
            for (int i = 0; i < currentSize; i++)
            {
                currClass = elementList[i].getClassName();
                
                if (currClass.equals(paramClass))
                {
                    if (elementList[i].equals(anElement) && flagged[i] == true)
                    {
                        System.out.println("Member found, but has already been"
                                + " flagged.");
                        return 1;
                    }
                    
                    else if (elementList[i].equals(anElement) && flagged[i] != true)
                    {
                        System.out.println("Member found and is now"
                                + " flagged.");
                        flagged[i] = true;
                        return 0;
                    }
                }
            }
            System.out.println("Member not found.");
            return -1;
        }
        
        //Declare flagIt method
        public int unFlagIt(Element anElement)
        {
            String paramClass = anElement.getClassName();
            String currClass;
            
            for (int i = 0; i < currentSize; i++)
            {
                currClass = elementList[i].getClassName();
                
                if (currClass.equals(paramClass))
                {
                    if (elementList[i].equals(anElement) && flagged[i] == true)
                    {
                        flagged[i] = false;
                        System.out.println("Member found, this member is no longer"
                                + " flagged");
                        return 1;
                    }
                    
                    else if (elementList[i].equals(anElement) && flagged[i] != true)
                    {
                        System.out.println("Member found, but is already "
                                + "unflagged");
                        return 0;
                    }
                }
            }
            System.out.println("Member not found.");
            return -1;    
        }
        
        //Declare universal class display method
        public void displayAllInClass(String theClassName)
        {
            if (currentSize == 0)
             {
                System.out.println("There are no members in the set. ");
             }
            else
            {           
                for (int i = 0; i < currentSize; i++)
                {        
                   if(theClassName.equals(elementList[i].getClassName()))
                   {
                       elementList[i].display();
                       System.out.println("\n");
                   }
                   
                   if(flagged[i] == true)
                   {
                       System.out.println("***ABOVE MEMBER HAS BEEN FLAGGED***");
                   }
                }
            }
        } 
    
    }
    Okay, so now that you've seen my code I'll just walk you through what I do that causes the error:

    I am presented with this menu:

    Java Code:
    -----------------------------
    Here are your Choices: 
    Enter 1 to add a Subscriber 
    Enter 2 to add an Application 
    Enter 3 to flag a Subscriber 
    Enter 4 to flag an Application 
    Enter 5 to unflag a Subscriber 
    Enter 6 to unflag and Application 
    Enter 7 to display all Subscribers 
    Enter 8 to display all Applications 
    Enter 9 to Quit 
    -----------------------------
    I choose 1 to add a subscriber, it works.

    I then choose 2 to add an application, it works.

    Here's where it gets hairy:

    When I attempt to flag or unflag while there are two different classes in the set OR if I attempt to flag/unflag an object from a class that isn't in the set (e.g. I only add subscriber, but not application and attempt to flag/unflag an application) I receive this error:

    Java Code:
    Exception in thread "main" java.lang.ClassCastException: assignment.pkg2.Application cannot be cast to assignment.pkg2.Subscriber
    	at assignment.pkg2.Assignment2.main(Assignment2.java:92)
    Java Result: 1
    and also the opposite depending on which option I choose:

    Java Code:
    Exception in thread "main" java.lang.ClassCastException: assignment.pkg2.Subscriber cannot be cast to assignment.pkg2.Application
    	at assignment.pkg2.Assignment2.main(Assignment2.java:113)
    Java Result: 1
    Referring to these lines:

    Java Code:
    anApp = (Application) anElement;
    Java Code:
    aSub = (Subscriber) anElement;
    The weird thing is, the program still flags/unflags the objects. It just fails right afterwards.

    Any ideas? Thanks a lot!

  2. #2
    DiamondSoul is offline Member
    Join Date
    Oct 2011
    Posts
    83
    Rep Power
    0

    Default Re: Strange error in my code, unsure what it is referring to.

    You shouldn't cast an object to a certain class unless you know for sure that said object is an instance of said class. You do this using the "instanceof" operator. In your code, you have a set of both Subscriber and Application objects. Before you cast an Element to either a Subscriber or and Application, you must check that it is an instance of the class you want.

    So, instead of this:
    Java Code:
    Subscriber aSub=(Subscriber)anElement; //throws an error if anElement is not a Subscriber
    //do stuff with aSub
    do this:
    Java Code:
    if(anElement instanceof Subscriber){ //make sure anElement is a Subscriber
        Subscriber aSub=(Subscriber)anElement;
        //do stuff with aSub
    }

  3. #3
    Scopic is offline Member
    Join Date
    Oct 2011
    Posts
    24
    Rep Power
    0

    Default Re: Strange error in my code, unsure what it is referring to.

    Ahh, I understand. Thank you.

    I will revise the code when I get home and will re-post any questions if necessary. Thanks again.

  4. #4
    DiamondSoul is offline Member
    Join Date
    Oct 2011
    Posts
    83
    Rep Power
    0

    Default Re: Strange error in my code, unsure what it is referring to.

    One more thing, I haven't looked super closely at your code, so I don't know if this comment applies to your program, but it's a good thing to keep in mind anyway.

    If you have a similar method in multiple subclasses of the same class, it's better to put that method in the superclass (and possibly make it abstract). For example, rather than doing this:

    Java Code:
    class A{
    }
    
    class B extends A{
        public String getInfo(){return "herp derp derp";}
    }
    
    class C extends A{
        public String getInfo(){return "FFFFFFFUUUUUUUUUUUU";}
    }
    It's better to do this:

    Java Code:
    abstract class A{
        public abstract String getInfo();
    }
    
    class B extends A{
        @Override
        public String getInfo(){return "herp derp derp";}
    }
    
    class C extends A{
        @Override
        public String getInfo(){return "FFFFFFFUUUUUUUUUUUU";}
    }
    Suppose you had an array of As which contained a mix of Bs and Cs. If you wanted to call getInfo on an arbitrary element in that array, using the former method, you'd have to check the element's type and cast it to that type before calling getInfo. However, using the latter method, you could simply say arr[index].getInfo(); and Java would automatically know which of the two implementations of getInfo to call based on the object's type.

Similar Threads

  1. Strange problem occurring with my code
    By Tech2011 in forum Eclipse
    Replies: 5
    Last Post: 10-13-2011, 10:30 AM
  2. strange error in eclipse
    By stevenpalomino in forum New To Java
    Replies: 29
    Last Post: 06-25-2011, 01:46 PM
  3. Colorchooser - Strange Exceptions in simple code.
    By spec8320 in forum AWT / Swing
    Replies: 3
    Last Post: 04-09-2011, 04:40 PM
  4. Strange Error
    By AJArmstron@aol.com in forum New To Java
    Replies: 1
    Last Post: 04-18-2010, 09:31 PM
  5. strange code
    By tghn2b in forum New To Java
    Replies: 3
    Last Post: 12-22-2008, 11:51 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •