Results 1 to 15 of 15
Like Tree2Likes
  • 1 Post By DarrylBurke
  • 1 Post By DarrylBurke

Thread: Variable Objects

  1. #1
    gogonimago is offline Member
    Join Date
    Feb 2012
    Posts
    17
    Rep Power
    0

    Default Variable Objects

    Hey guys, I have a question.

    In the code below, you can see that I want to ask the player to choose one of three classes. If the player chooses class 1, I create a class 1 object, if it's class two, I create a class two object. But when I try to do something with those objects, I get a compiler error saying no object exists with that name. I understand why this happens, because there are 3 if statements which have to run in order for the objects to be created, but what is a way around this. How can I use the object which I create in an if statement?

    Java Code:
    import java.util.Scanner;
    
    public class RPGMain {	  
    	
    	public static void main(String[] args){				 
    		 RPGMain main = new RPGMain();
    		 main.chooseClass();
    	 }
    	 
    	 void incorrect(String x){
    		 if (x.contentEquals("classError")){
    			 System.out.println("That is not a valid class");
    			 chooseClass();
    		 }
    	 }
    	 
    	 void chooseClass(){		
    		Scanner input = new Scanner(System.in);
    		String y = "classError";		
    		System.out.println("Choose your class: \n Type in 'warrior' for a warrior class \n Type in 'archer' for an archer class \n Type in 'mage' for a mage class");
    		String userClass = input.nextLine();
    		if(userClass.contentEquals("warrior") ){		
    			warrior character = new warrior();	
    			System.out.println("You are now a warrior!");
    		} else if (userClass.contentEquals("archer")){			
    			archer character = new archer();
    			System.out.println("You are now an archer!");
    		} else if (userClass.contentEquals("mage")){			
    			mage character = new mage();
    			System.out.println("You are now a mage!");
    		} else{
    			incorrect(y);		
    		}			
    		
    		while(true){
    		   System.out.println("You are now faced with several options: \n 1 - Type in 'go' or anything else not on this list to continue \n 2 - Type in 'level up' to level up \n 3 - Type in 'exit' to exit");
    		   String conntinue = input.nextLine();		   
    		   if(conntinue.contentEquals("level up")) {
    			 character.levelUp();
         	   } else if (conntinue.contentEquals ("exit")) {
         		   System.exit(0);
         	   }
    	    }
    	}
    }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: Variable Objects

    I get a compiler error
    Please post the full text of the error message here.

    How can I use the object which I create in an if statement?
    You need to define the variables that hold references to the objects at a scope where they can be seen by all the code that needs to use them.
    You can assign values to those variables anywhere you need to, like in your if statements.
    Define at a top level of scope
    Assign values anywhere.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,452
    Rep Power
    20

    Default Re: Variable Objects

    Your code is extremely difficult to follow on account of your not observing code conventions. Class names begin with an uppercase letter.

    Also, your question is unanswerable unless you provide some detail of the inheritance hierarchy: do the three classes have a common superclass or implement a common interface, one that has a levelUUp() method inherited by them?

    Note that variables exist only in the scope in which they are defined: the { and }

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  4. #4
    gogonimago is offline Member
    Join Date
    Feb 2012
    Posts
    17
    Rep Power
    0

    Default Re: Variable Objects

    I understand that I need to declare the variable, but when I tried it, it obviously couldn't convert from like a warrior to an archer or to a mageclass.

    This is what I tried doing at the top of the class to declare the object and it obviously didn't work.

    Java Code:
    warrior character = new warrior();

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: Variable Objects

    it obviously didn't work.
    Please explain and post the full text of any error messages.

    BTW Classname names should start with uppercase letters.

  6. #6
    gogonimago is offline Member
    Join Date
    Feb 2012
    Posts
    17
    Rep Power
    0

    Default Re: Variable Objects

    I apologize for my mistakes. I am very new to java and have only read Head First Java. I will be more careful from now on.

    As for the inheritance tree, yes, they do have a superclass, which I know that I can make an object of as a declaration and then modify it into specific subclasses such as warrior or mage, but isn't that also considered bad programming? Like what would be in the constructor for that class? The only things there are some methods that the three main classes share, here, I'll post it:

    Java Code:
    import java.util.Scanner;
    
    public abstract class heroClasses{
    	int health;
    	int damage;
    	int levelPoints;
    	int numberOfPointsChosen;
    	boolean farDamage;	
    
    	Scanner userInput = new Scanner(System.in);
    	
    	public void levelUpDisp(){
    		System.out.println("You have " + levelPoints + " points to use to level up skills");		
    	}
    	
    	public void levelUpHealth(){		
    		levelUpDisp();
    		System.out.println("You chose to level up your health");
    		System.out.println("How many points would you like to use to level up?");		
    		numberOfPointsChosen = userInput.nextInt();		
    		if (numberOfPointsChosen > levelPoints){
    			System.out.println("You can't do that, you don't have enough points");
    			numberOfPointsChosen = 0;
    		}					
    		health += numberOfPointsChosen;
    		levelPoints -= numberOfPointsChosen;
    		System.out.println("Your health is now " + health);
    		System.out.println("You are left with " + levelPoints + " points for leveling up");		
    		
    	}
    	
    	public void levelUpDamage(){
    		levelUpDisp();
    		System.out.println("You chose to level up your damage");
    		System.out.println("How many points would you like to use to level up?");		
    		numberOfPointsChosen = userInput.nextInt();	
    		if (numberOfPointsChosen > levelPoints){
    			System.out.println("You can't do that, you don't have enough points");
    			numberOfPointsChosen = 0;
    		}		
    		damage += numberOfPointsChosen;
    		levelPoints -= numberOfPointsChosen;
    		System.out.println("Your damage is now " + damage);
    		System.out.println("You are left with " + levelPoints + " points for leveling up");		
    	}
    	
    	public void gainLevel(int monsterLevel){
    		levelPoints += monsterLevel;
    		//called when an enemy is killed
    	}
    	
    	public void attack(){
    		//code to take damage from enemy's health
    	}
    	
    	public void getHit(){
    		//health =- enemy damage
    	}
    	
    	public void death(){
    		System.out.println("You are dead!");		
    	}
    }

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: Variable Objects

    Are your problems fixed now?

    BTW Classname names should start with uppercase letters.

  8. #8
    gogonimago is offline Member
    Join Date
    Feb 2012
    Posts
    17
    Rep Power
    0

    Default Re: Variable Objects

    This is my new code:

    Java Code:
    import java.util.Scanner;
    
    public class RPGMain {	
    	mage character = new mage(); 
    	public static void main(String[] args){				 
    		 RPGMain main = new RPGMain();
    		 main.chooseClass();
    	 }
    	 
    	 void incorrect(String x){
    		 if (x.contentEquals("classError")){
    			 System.out.println("That is not a valid class");
    			 chooseClass();
    		 }
    	 }
    	 
    	 void chooseClass(){		
    		Scanner input = new Scanner(System.in);
    		String y = "classError";		
    		System.out.println("Choose your class: \n Type in 'warrior' for a warrior class \n Type in 'archer' for an archer class \n Type in 'mage' for a mage class");
    		String userClass = input.nextLine();
    		if(userClass.contentEquals("warrior") ){			
    			character = new warrior();
    			System.out.println("You are now a warrior!");
    		} else if (userClass.contentEquals("archer")){			
    			character = new archer();
    			System.out.println("You are now an archer!");
    		} else if (userClass.contentEquals("mage")){			
    			character = new mage();
    			System.out.println("You are now a mage!");
    		} else{
    			incorrect(y);		
    		}			
    		
    		while(true){
    		   System.out.println("You are now faced with several options: \n 1 - Type in 'go' or anything else not on this list to continue \n 2 - Type in 'level up' to level up \n 3 - Type in 'exit' to exit");
    		   String conntinue = input.nextLine();		   
    		   if(conntinue.contentEquals("level up")) {
    			 character.levelUp();
         	   } else if (conntinue.contentEquals ("exit")) {
         		   System.exit(0);
         	   }
    	    }
    	}
    }

    All I added was the statement
    Java Code:
    mage character = new mage();
    at the top, above where I made the main class. Also instead of creating a new object in the if statements, I just tried to reassign the "character" reference variable to whatever object I needed to create. This came up with the following error:


    Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    Type mismatch: cannot convert from warrior to mage
    Type mismatch: cannot convert from archer to mage

    at RPGMain.chooseClass(RPGMain.java:23)
    at RPGMain.main(RPGMain.java:7)


    I understand why the above error happens but I don't know the way around it.

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: Variable Objects

    Type mismatch: cannot convert from warrior to mage
    The compiler does not think those classes are the same.
    Is a Warrior an instance of the Mage class?
    You are trying to assign a Warrior to character which is a Mage.
    And the same problem with Archer.

    BTW Classname names should start with uppercase letters.

  10. #10
    gogonimago is offline Member
    Join Date
    Feb 2012
    Posts
    17
    Rep Power
    0

    Default Re: Variable Objects

    Yes, I understand all of that but how do I get around it? How can I ask the user to choose one of three classes and, based on the results, make one of the three different objects and then use the reference variable of this object?

  11. #11
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,452
    Rep Power
    20

    Default Re: Variable Objects

    The three classes must share a common Type. You do this by either inheriting form a common superclass (possibly abstract) or by implementing a common interface.

    db
    Tolls likes this.
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,185
    Rep Power
    20

    Default Re: Variable Objects

    Declare 'character' as a Hero (I'd rename heroClasses personally), since that is the superclass you want to work with.
    Do not bother instantiating it (ie no 'new Mage()' or anything).
    You only want to go into the 'while(true)' loop if they have selected a valid character type, so you need to change your character selection code to loop until a valid one is selected (or some exit condition).
    I'd stick the selection code in its own method that returns a boolean to show the character has been created.
    If true then do the while loop (which I'd have in its own method as well).

    You're quite close, you just haven't grasped using your inheritance yet.

  13. #13
    gogonimago is offline Member
    Join Date
    Feb 2012
    Posts
    17
    Rep Power
    0

    Default Re: Variable Objects

    Quote Originally Posted by Tolls View Post
    You only want to go into the 'while(true)' loop if they have selected a valid character type, so you need to change your character selection code to loop until a valid one is selected (or some exit condition).
    I did that, where I ask the player to type in one of the three classes, if they don't choose a correct class, I print out an error message and then restart the method, I tested it and everything it works.

    Quote Originally Posted by Tolls View Post
    Declare 'character' as a Hero (I'd rename heroClasses personally), since that is the superclass you want to work with.
    Do not bother instantiating it (ie no 'new Mage()' or anything).
    If I don't bother instantaining it, how can I make a mage or an archer?

  14. #14
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,452
    Rep Power
    20

    Default Re: Variable Objects

    Java Code:
    SuperClass spr = null;
    if (something1) {
      spr = new SubClass1();
    } else if (something2) {
      spr = new SubClass2();
    } ....
    
    spr.methodDefinedInSuperType();
    db
    gogonimago likes this.
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  15. #15
    gogonimago is offline Member
    Join Date
    Feb 2012
    Posts
    17
    Rep Power
    0

    Default Re: Variable Objects

    Thank you very much for the straight answer! I have successfully solved my problem thanks to you Mr. Burke !

Similar Threads

  1. Dynamic variable name based on other variable
    By nadissen in forum Eclipse
    Replies: 4
    Last Post: 05-06-2011, 07:22 PM
  2. Objects and Classes cannot find symbol variable.
    By argnsoccer in forum New To Java
    Replies: 22
    Last Post: 10-28-2010, 01:23 AM
  3. Replies: 11
    Last Post: 07-07-2010, 07:02 AM
  4. Array of objects, as an Instance variable
    By blaklite in forum New To Java
    Replies: 2
    Last Post: 03-25-2009, 01:56 AM
  5. Replies: 1
    Last Post: 01-22-2009, 05:25 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
  •