PDA

View Full Version : how to fix ClassCastException


shadylookin
07-01-2007, 11:57 PM
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
Items item = (Items) scanner.nextLine();

I tried doing it this way

Object itemToBeUsed = (Object) scanner.nextLine();
Items item = (Items) itemToBeUsed;

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?

here is a snippet of my actual 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);}


any help would be appreciated

brad211987
07-02-2007, 01:03 AM
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 way you could use the code:


String itemString = itemToUse.nextLine();
Items item = new Items(itemString);


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.

Hope this helps.

shadylookin
07-02-2007, 01:11 AM
here is my Items class code

package finalproject;

public interface Items {

public void useItem(Game game);




}

it's an interface, but here is a class that implements Items


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);
}
}

}

brad211987
07-02-2007, 01:46 AM
Ok, judging from the class names, I'm going to assume you will have more classes that implement Items. You should be able to take your itemString and do a select...case block for the different item types. Each case can call the method for the corresponding item. I would make the useItem method static for each items class also.

So in psuedo code:


select itemString
case health potion
HealthPotion.useItem(game)
case potion type 2
.....
case potion type 3
.....