Results 1 to 3 of 3
Thread: ClassCastException
- 07-04-2007, 04:57 AM #1
Member
- Join Date
- Jun 2007
- Posts
- 95
- Rep Power
- 0
ClassCastException
I'm trying to write a small text based game. I decided I would like to add items to the game. When using the Scanner I'm trying to turn a String into an Items.
since I cannot cast
I tried doing it this wayJava Code:Items item = (Items) scanner.nextLine();
the complier is fine with that, but at runTime it gives me a ClassCastException when I try and use it. How should I go about fixing this?Java Code:Object itemToBeUsed = (Object) scanner.nextLine(); Items item = (Items) itemToBeUsed;
any help? Thanks.Java Code:else if(cmd.equalsIgnoreCase("take")){ Scanner itemToTake = new Scanner(System.in); Object itemBeingTaken = itemToTake.nextLine(); Items item = (Items) itemBeingTaken; return "" +this.location.take(this, item); } else if(cmd.equalsIgnoreCase("use")){ Scanner itemToUse = new Scanner(System.in); System.out.println("what item would you like to use?"); Object itemString = itemToUse.nextLine(); Items item = (Items) itemString; return ""+ useItemFromInventory(item);}
Felissa:p
- 07-04-2007, 04:59 AM #2
Member
- Join Date
- Jun 2007
- Posts
- 92
- Rep Power
- 0
What this means is, at runtime, java cannot convert from class Object to class Items. What I would do, is use the constructor in the Items class to accept your string value and use that to create your Items object.
This would avoid the nasty type casting and in my opinion provide cleaner code. I don't know how practical this is for you, as I don't know what your Items class looks like.Java Code:String itemString = itemToUse.nextLine(); Items item = new Items(itemString);
Greetings.
Marcus:cool:
- 07-04-2007, 05:06 AM #3
Member
- Join Date
- Jun 2007
- Posts
- 95
- Rep Power
- 0
here is my Items class code:
it's an interface, but here is a class that implements ItemsJava Code:package finalproject; public interface Items { public void useItem(Game game); . . . }
Thanks!Java Code:package finalproject; public class HealthPotion implements Items{ public void useItem(Game game){ int health = game.getHealth() + 50; if(health >= 100){ game.setHealth(100); System.out.println("your health has increase to 100"); } else{ game.setHealth(health); System.out.println("your health has increased to "+ health); } } }
Felissa:p
Similar Threads
-
ClassCastException in TreeSet
By pHew in forum New To JavaReplies: 2Last Post: 01-16-2008, 12:20 AM -
Problem with vector, java.lang.ClassCastException
By paul in forum New To JavaReplies: 1Last Post: 07-16-2007, 04:31 PM -
ClassCastException
By Ed in forum New To JavaReplies: 2Last Post: 07-04-2007, 05:26 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks