Home arrow static arrow Java Programming [Archive] - ClassCastException and I don't know why
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - ClassCastException and I don't know why
This topic has 12 replies on 1 page.

Posts:23
Registered: 8/4/03
ClassCastException and I don't know why  
Aug 4, 2004 12:02 PM



 
I have a program to which I can add different components and/or a complete PC to a linkedlist. When I add a component such as CPU, it has four attributes, maker, model, speed, price. It works fine, i can show the components in my list, i can remove a component and even search after a specific maker/model.
I can also add a complete PC to my list, which consists of another linkedlist, which consists of maker, model, CPU, Motherboard, Harddrive, and Ram. The CPU, motherboard, harddrive, and ram is like the components.

The problem occurs when i add a second complete PC to the list, it then throws the ClassCastException.

This is how i calculate the the price for a complete pc:
public void beregnPris()	{		int totalPris = 0;		ListIterator temporaryComponents = myTemporaryPC.listIterator();		while (temporaryComponents.hasNext())		{				Component temporary = (Component) temporaryComponents.next();			int pris = temporary.pris;			totalPris = totalPris + pris;		}							Integer prisen = new Integer(totalPris);		myTemporaryPC.add("\n\nSamlet pris: " + prisen);// the problem occurs before this line of code		myHardware.addFirst(myTemporaryPC);}


this is what my component class looks like. I have left a bit about, but it is similar to the CPU class, except for my compareTO, and equals methods.
public class Component implements Comparable{	public String fabrikant;	public String model;	public String frekvens;	public String information;	public String stoerrelse;	public int pris;	 		public Component()	{		}		class CPU extends Component 	{				public CPU(String f, String m, String z, int p)		{			fabrikant = f;			model = m;			frekvens = z;			pris = p;		}									public String toString()		{			return("\n 'Fabrikant' " + fabrikant + 			" 'Model' " + model + 			" 'Frekvens' " + frekvens + 			" 'Pris' " + pris);		}		}}
 

Posts:3,258
Registered: 00-08-28
Re: ClassCastException and I don't know why  
Aug 4, 2004 12:09 PM (reply 1 of 12)



 
could you print the stack trace
 

Posts:2,206
Registered: 8/15/02
Re: ClassCastException and I don't know why  
Aug 4, 2004 12:14 PM (reply 2 of 12)



 
Which Component class are you casting to? If it's java.awt.Component, then that's your problem. If you component class is in a package, explicity use the package name to remove ambiguity (or chnage the name of your Component class)
 

Posts:23
Registered: 8/4/03
Re: ClassCastException and I don't know why  
Aug 4, 2004 12:21 PM (reply 3 of 12)



 
this is the files that is of use, i have to more files, one to start the program, and one with a keyboardlistener
public class Component implements Comparable{	public String fabrikant;	public String model;	public String frekvens;	public String information;	public String stoerrelse;	public int pris;	 		public Component()	{		}		class CPU extends Component 	{				public CPU(String f, String m, String z, int p)		{			fabrikant = f;			model = m;			frekvens = z;			pris = p;		}									public String toString()		{			return("\n 'Fabrikant' " + fabrikant + 			" 'Model' " + model + 			" 'Frekvens' " + frekvens + 			" 'Pris' " + pris);		}		}		class Bundkort extends Component	{		public Bundkort(String f, String m, String i, int p)		{			fabrikant = f;			model = m;			information = i;			pris = p;					}				public String toString()		{			return("\n 'Fabrikant' " + fabrikant + 			" 'Model' " + model + 			" 'Information' " + information + 			" 'Pris' " + pris);		}		}		class Harddisk extends Component	{		public Harddisk(String f, String m, String s, int p)		{			fabrikant = f;			model = m;			stoerrelse = s;			pris = p;		}				public String toString()		{			return("\n 'Fabrikant' " + fabrikant + 			" 'Model' " + model + 			" 'St�rrelse' " + stoerrelse + 			" 'Pris' " + pris);		}		}		class Ram extends Component	{		public Ram(String f, String m, String s, int p)		{			fabrikant = f;			model = m;			stoerrelse = s;			pris = p;			}				public String toString()		{			return("\n 'Fabrikant' " + fabrikant + 			" 'Model' " + model + 			" 'St�rrelse' " + stoerrelse + 			" 'Pris' " + pris);		}		}		class PC extends Component	{		public PC(String f, String m)		{			fabrikant = f;			model = m;		}				public String toString()		{			return("'Fabrikant' " + fabrikant + 					" 'Model' " + model);		}			}		public boolean equals(Object object)	{			if (compareTo(object) == 0)			{				return true;			}			else return false;	}		public int compareTo(Object object)	{		Component del = ((Component) object);		if(fabrikant.equals(del.fabrikant))		{			if (model.equals(del.model))			{				return 0;			}			return 1;		}		else return 1;	}	}


import corejava.Console;  public class UserInterface{	WareHouse wareHouseObject = new WareHouse();	Console inputFromKeyboard = new Console();	Component comp = new Component();		/*En metode som rydder sk�rmen.*/	private void waitAndClear()	{		System.out.println("Invalid input...");		Console.readString("Press <enter> to continue...");		System.out.println();		}		/*This method is the one which get the program started. Its the functionality of the	main menu, it is from here it calls the other methods in the program, according to	the user input. It calls a method which prints the options in the main menu.*/	public void startProgram()	{		String result;		boolean keepRunning = true;				do		{			result = this.showMainMenu();						if(result.equals("0")) keepRunning = false;			else if(result.equals("1")) this.addHardware();			else if(result.equals("2")) this.removeHardware();			else if(result.equals("3")) this.showMyHardware();			else if(result.equals("4")) this.searchForHardware();			else						this.waitAndClear();		}		while(keepRunning);	}	/*This is text in the main menu, it reads the input from the user, and the returns it to the 	startProgram method, which then acts according to the input*/	private String showMainMenu()	{		System.out.println("\n --- MyHardware A/S --- \n");		System.out.println(" 1) - Add hardware to inventory.");		System.out.println(" 2) - Remove hardware from inventory.");		System.out.println(" 3) - Show current inventory.");		System.out.println(" 4) - Search for hardware or PC.");		System.out.println(" 0) - Terminate program.");		System.out.print(" \n -> ");		return Console.readString();	}		private void addHardware()	{		int outputForLoop = 6;				do		{			int typeOfHardware = inputFromKeyboard.readInt("What do you want to add? \n\n" +															" Press 1 for CPU\n" +															" Press 2 for Motherboard\n" +															" Press 3 for Harddisk\n" +															" Press 4 for Ram\n" +															" Press 5 for PC\n" +															" Press 0 to cancel\n\n" +															" -> ");					switch (typeOfHardware)			{			case 1:				wareHouseObject.addNewCPU(comp.new CPU(this.fabrikant(), 				this.model(), this.frekvens(), this.pris()));				outputForLoop = 1;				break;			case 2:				wareHouseObject.addNewBundkort(comp.new Bundkort(this.fabrikant(), 				this.model(), this.information(), this.pris()));				outputForLoop = 2;				break;			case 3:				wareHouseObject.addNewHD(comp.new Harddisk(this.fabrikant(), 				this.model(), this.stoerrelse(), this.pris()));				outputForLoop = 3;				break;			case 4:				wareHouseObject.addNewRam(comp.new Ram(this.fabrikant(), 				this.model(), this.stoerrelse(), this.pris()));				outputForLoop = 4;				break;			case 5:				wareHouseObject.addNewPC(comp.new PC(this.fabrikant(), this.model()));				wareHouseObject.addNewPCCPU(comp.new CPU(this.fabrikant(), this.model(), 				this.frekvens(), this.pris()));										int input1;				do				{					input1 = inputFromKeyboard.readInt(" Vil du tilf�je endnu en CPU ? \n" +					"(1) - Ja \n (0) - Nej \n ->");					switch (input1)					{						case 1:							wareHouseObject.addNewPCCPU(comp.new CPU(this.fabrikant(), 							this.model(), this.frekvens(), this.pris()));							outputForLoop = 2;							break;						case 0:							outputForLoop = 0;							break;						default:							System.out.println("Tryk enten 1 eller 0.");							outputForLoop = 2;					}				}							while (outputForLoop == 2);								wareHouseObject.addNewPCBundkort(comp.new Bundkort(this.fabrikant(), 				this.model(), this.information(), this.pris()));								wareHouseObject.addNewPCHarddisk(comp.new Harddisk(this.fabrikant(), 				this.model(), this.stoerrelse(), this.pris()));								int input2;				do				{					input2 = inputFromKeyboard.readInt(" Vil du tilf�je endnu en harddisk ? " +					"\n (1) - Ja \n (0) - Nej \n ->");					switch (input2)					{						case 1:							wareHouseObject.addNewPCHarddisk(comp.new Harddisk(this.fabrikant(), 							this.model(), this.stoerrelse(), this.pris()));							outputForLoop = 2;							break;						case 0:							outputForLoop = 0;							break;						default:							System.out.println("Tryk enten 1 eller 0.");							outputForLoop = 2;					}				}							while (outputForLoop == 2);											wareHouseObject.addNewPCRam(comp.new Ram(this.fabrikant(), this.model(), 				this.stoerrelse(), this.pris()));								int input3;				do				{					input3 = inputFromKeyboard.readInt(" Vil du tilf�je mere ram ? \n " +					"(1) - Ja \n (0) - Nej \n ->");					switch (input3)					{						case 1:							wareHouseObject.addNewPCRam(comp.new Ram(this.fabrikant(), 							this.model(), this.stoerrelse(), this.pris()));							outputForLoop = 2;							break;						case 0:							outputForLoop = 0;							break;						default:							System.out.println("Tryk enten 1 eller 0.");							outputForLoop = 2;					}				}							while (outputForLoop == 2);			//	wareHouseObject.beregnPris();				outputForLoop = 5;				break;			case 0:				outputForLoop = 99;				break;			default:				outputForLoop = 6;			}		} 		while(outputForLoop == 6);				}		private void removeHardware()	{		this.showMyHardware();		int input = inputFromKeyboard.readInt("\nIndtast nummer p� det hardware du vil " +		"fjerne fra listen: ->");		wareHouseObject.removeComponent(input);	}		private void showMyHardware()	{		wareHouseObject.displayMyHardware();	}		private void searchForHardware()	{		String fabrikantToSearchFor = inputFromKeyboard.readString(" Fabrikant -> ");		String modelToSearchFor = inputFromKeyboard.readString(" Model -> ");				wareHouseObject.searchHardware(fabrikantToSearchFor, modelToSearchFor);	}		public String fabrikant()	{		String fabrikant = inputFromKeyboard.readString(" Fabrikant -> ");		return fabrikant;	}		public String model()	{		String model = inputFromKeyboard.readString(" Model -> ");		return model;	}		public int pris()	{		int pris = inputFromKeyboard.readInt(" Pris -> ");		return pris;	}		public String frekvens()	{		String frekvens = inputFromKeyboard.readString(" Frekvens -> ");		return frekvens;	}	public String information()	{		String information = inputFromKeyboard.readString(" Information -> ");		return information;	}		public String stoerrelse()	{		String stoerrelse = inputFromKeyboard.readString(" St�rrelse -> ");		return stoerrelse;	} }


import java.util.*;import java.util.LinkedList;import corejava.Console;  public class WareHouse{	public LinkedList myHardware = new LinkedList();	public LinkedList myTemporaryPC = new LinkedList();	Component comp = new Component();				public void addNewCPU(Component.CPU newCPU)	{		int temporary = myHardware.indexOf(newCPU);			if (temporary == -1)		{			myHardware.addFirst(newCPU);		} 	}		public void addNewBundkort(Component.Bundkort newBundkort)	{		int temporary = myHardware.indexOf(newBundkort);		if (temporary == -1)		{			myHardware.addFirst(newBundkort);		}	}		public void addNewHD(Component.Harddisk newHD)	{		int temporary = myHardware.indexOf(newHD);		if (temporary == -1)		{			myHardware.addFirst(newHD);		}	}		public void addNewRam(Component.Ram newRam)	{		int temporary = myHardware.indexOf(newRam);		if (temporary == -1)		{			myHardware.addFirst(newRam);		}	}		public void addNewPC(Component.PC newPC)	{		myTemporaryPC.add(newPC);	}		public void addNewPCCPU(Component.CPU newCPU)	{		myTemporaryPC.add(newCPU);	}		public void addNewPCBundkort(Component.Bundkort newBundkort)	{		myTemporaryPC.add(newBundkort);	}		public void addNewPCHarddisk(Component.Harddisk newHD)	{		myTemporaryPC.add(newHD);	}		public void addNewPCRam(Component.Ram newRam)	{		myTemporaryPC.add(newRam);		myHardware.addFirst(myTemporaryPC);		}			public void removeComponent(int input)	{		myHardware.remove(input);	}				public void displayMyHardware()	{		int i = 0;		ListIterator components = myHardware.listIterator();		while (components.hasNext())		{						System.out.println(i + " " + components.next());			i++;		}	}		public void searchHardware(String f, String m)	{		ListIterator components = myHardware.listIterator();		while (components.hasNext())		{			Component temporary = (Component) components.next();			String fabrikant = temporary.fabrikant;			String model = temporary.model;						if (f.equals(fabrikant) && m.equals(model)) 			{				System.out.print(temporary + "\n\n\n");			}		}	}			public void beregnPris()	{		int totalPris = 0;		ListIterator temporaryComponents = myTemporaryPC.listIterator();		while (temporaryComponents.hasNext())		{				Component temporary = (Component) temporaryComponents.next();			int pris = temporary.pris;			totalPris = totalPris + pris;		}							Integer prisen = new Integer(totalPris);		myTemporaryPC.add("\n\nSamlet pris: " + prisen);		myHardware.addFirst(myTemporaryPC);	}}

 

Posts:105
Registered: 6/8/04
Re: ClassCastException and I don't know why  
Aug 4, 2004 1:07 PM (reply 4 of 12)



 
		myTemporaryPC.add("\n\nSamlet pris: " + prisen);// the problem occurs before this line of code


That's your problem line. You're adding a String to your List; the other objects in there are Components. Then, when you add a second PC to the List, you run into this line:

			Component temporary = (Component) temporaryComponents.next();


Here, you try to cast the Object into a Component; at some point, I'm guessing you run into the String you added, hence the ClassCastException.

That's my first guess, at least; I didn't go through all your code (by the way, posting all your code and expecting someone to go through it all is generally not a good idea; try to just isolate the problem part. Also, be sure to give the stack trace when you have an Exception being thrown, and be sure to point out what line the Exception is thrown from!)
 

Posts:23
Registered: 8/4/03
Re: ClassCastException and I don't know why  
Aug 4, 2004 1:15 PM (reply 5 of 12)



 
Well i added all the code, since i thought that it could help somebody reading what my problem was, especially when i had pointed out what I thought was the problem..

anyways here's the stack trace
java.lang.ClassCastException 	at WareHouse.searchHardware(WareHouse.java:108) 	at UserInterface.searchForHardware(UserInterface.java:213) 	at UserInterface.startProgram(UserInterface.java:43) 	at RunMe.main(RunMe.java:8)
 

Posts:105
Registered: 6/8/04
Re: ClassCastException and I don't know why  
Aug 4, 2004 1:24 PM (reply 6 of 12)



 
Ah, that stack trace is helfpul. As you can see, it's pointing at the searchHardware method, line 108 which I'm guessing is:

Component temporary = (Component) components.next();


You're casting an Object that was added to myHardware into a Component. However, earlier, you added a LinkedList to myHardware:

myHardware.addFirst(myTemporaryPC);


So, basically you're adding a LinkedList to myHardware, whereas based on your code you only want myHardware to contain Components. The exception is thrown when you try to turn the LinkedList into a Component.
 

Posts:23
Registered: 8/4/03
Re: ClassCastException and I don't know why  
Aug 4, 2004 1:29 PM (reply 7 of 12)



 
that is what i was afraid of. Is there any way to go around this, or is it some sort of unsolveable problem?
 

Posts:2,206
Registered: 8/15/02
Re: ClassCastException and I don't know why  
Aug 4, 2004 1:33 PM (reply 8 of 12)



 
Object x = something.next();if ( x instanceof Component ) {    // do something}// get the next item
 

Posts:105
Registered: 6/8/04
Re: ClassCastException and I don't know why  
Aug 4, 2004 1:55 PM (reply 9 of 12)



 
that is what i was afraid of. Is there any way to go around this, or is it some sort of unsolveable problem?

EvilEdna's solution will work, but the core of the problem is poor design. Why is it that you're adding a LinkedList to a list of Components? Heck, what's supposed to be in myTemporaryPC anyway? You could, as Edna is suggesting, simply skip over the troublesome spots, but really the question is why are you putting the troublesome spots in in the first place?

I'd say, based on the cursory glance I've taken of the code, what you should do is create a class Computer that also extends Component, and contains a bunch of Components within itself--the CPU, the harddrive, etc. Give it a constructor by which it takes in a LinkedList of Components. Then, instead of adding myTemporaryPC to myHardware, add new Computer(myTemporaryPC) to myHardware.

But it all comes down to a question of what you're trying to accomplish by adding it in the first place. This is a question of design--one that you must answer.
 

Posts:2,206
Registered: 8/15/02
Re: ClassCastException and I don't know why  
Aug 4, 2004 2:07 PM (reply 10 of 12)



 
Course you could go to 1.5, and then you won't be able to add anything except a Component.
 

Posts:23
Registered: 8/4/03
Re: ClassCastException and I don't know why  
Aug 4, 2004 2:50 PM (reply 11 of 12)



 
I'd say, based on the cursory glance I've taken of the
code, what you should do is create a class Computer
that also extends Component, and contains a bunch of
Components within itself--the CPU, the harddrive, etc.
Give it a constructor by which it takes in a
LinkedList of Components. Then, instead of adding
myTemporaryPC to myHardware, add new
Computer(myTemporaryPC) to myHardware.

how would you do that, I'm trying to do so now, but it seems like i can't do it correctly
I only have 10 hours until I have to hand in this assignment for my exam, so please help me
 

Posts:23
Registered: 8/4/03
Re: ClassCastException and I don't know why  
Aug 4, 2004 3:25 PM (reply 12 of 12)



 
now i get a compile error saying:
UserInterface.java:19: an enclosing instance that contains Component.Computer is required 		compu = new Component.Computer();


it seems like I can't make a call to the CPU compunent in the Computer class
my structure now looks like
[code]
public class Component implements Comparable
{
public Component()
{
}
class CPU extends Component
{
public CPU(String f, String m, String z, int p)
{
...
}
}
...
class Computer extends Component
{
public Computer(String f, String m)
{
//not quite sure what to have here. But added a super();
}
class CPU extends Component
{
public CPU(String f, String m, String z, int p)
{
...
}
}
...
}
}
 
This topic has 12 replies on 1 page.