Page 1 of 2 12 LastLast
Results 1 to 20 of 21
  1. #1
    bobleny's Avatar
    bobleny is offline Member
    Join Date
    Apr 2008
    Posts
    50
    Rep Power
    0

    Default [SOLVED] Creating an object within a if statement that carries out?

    I want to make an object named level based on what the user enters. What the user enters is controlled, it will be either a 1, 2, or a 3.

    It looks much like this:
    Java Code:
    public class SecretPhrase
    {
       public static void main(String[] args)
       {
           int option;
           
           option = 1;
           if(option == 1)
           {
               Easy level = new Easy();
           }
           else if(option == 2)
           {
               //Medium level = new Medium();
           }
           else if(option == 3)
           {
               //Hard level = new Hard();
           }
           
           /** The Problem --> */ level.getRandom();
       }
    }
    The problem is, the Java compiler doesn't think it exists. If I declare level outside of the if statements, no problems....

    I simply want to make a Hard object named level, or an Easy object named level, or a Medium object named level based on which level the user wants.

    Is there a way to do this?

    Thanks!
    --------------------------------------------------------------------
    More information!

    I didn't think it necessary to do this, but here is the entire story. I thought that this would confuse the situation more than help it, so I never put all on here.

    I have one super class: Phrase
    I have three sub classes: Easy, Medium, and Hard
    I have one main class: SecretPhrase (Will eventually be an applet!)

    Phrase:
    Java Code:
    import java.util.Random;
    
    public class Phrase
    {
        private Random ran;
        private int ans;
        private int ranNum;
        
        public Phrase()
        {
        }
        
        public String getPhrase(int x)
        {
            String joe = "0";
            return joe;
        }
        
        public int getRandom(int phrasesLength)
        {
            
            boolean x = false;
            while(x != true)
            {
                ran = new Random();
                double num = ran.nextDouble();
                ans = (int) (num / .01);
                if((ans >= 0) && (ans <= phrasesLength))
                {
                    break;
                }
            }
            return ans;
        }
    }


    As of right now, Easy, Medium, and Hard are Exactly the same, there will be little differences between these three classes.
    Easy, Medium, and Hard:
    Java Code:
    public class Easy extends Phrase
    {
        static String[] phrases;
        
        public Easy()
        {
    	   phrases = new String[25];
            
            //Phrases
             phrases[0] = "Elephant";
             phrases[1] = "Cat";
             phrases[2] = "Deer";
             phrases[3] = "Rabbit";
             phrases[4] = "Monkey";
             phrases[5] = "Moose";
             phrases[6] = "Crocodile";
             phrases[7] = "Snake";
             phrases[8] = "Goat";
             phrases[9] = "Lion";
            phrases[10] = "Dog";
            phrases[11] = "Bird";
            phrases[12] = "Mouse";
            phrases[13] = "Bat";
            phrases[14] = "Bear";
            phrases[15] = "Sheep";
            phrases[16] = "Snail";
            phrases[17] = "Shark";
            phrases[18] = "Frog";
            phrases[19] = "Spider";
            phrases[20] = "Tiger";
            phrases[21] = "squid";
            phrases[22] = "Octopus";
            phrases[23] = "Worm";
            phrases[24] = "Fish";
        }
        
        public void getRandom()
        {
            super.getRandom(phrases.length);
        }
    }

    SecretPhrase: See above.
    Last edited by bobleny; 04-24-2008 at 09:32 PM.
    -- www.firemelt.net --
    Cheer up, the worst has yet to come...

  2. #2
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    Object reference only valid within the loops. So you have to declared outside of loops. Instantiate within the loop. Got it.

  3. #3
    bobleny's Avatar
    bobleny is offline Member
    Join Date
    Apr 2008
    Posts
    50
    Rep Power
    0

    Default

    Quote Originally Posted by Eranga View Post
    Object reference only valid within the loops. So you have to declared outside of loops. Instantiate within the loop. Got it.
    OK, so then is there a way to declare the object outside of my if statement and still call it level?
    -- www.firemelt.net --
    Cheer up, the worst has yet to come...

  4. #4
    DonCash's Avatar
    DonCash is offline Moderator
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    240
    Rep Power
    8

    Default

    Hey bobleny,

    The easiest way is to do it like this:

    Java Code:
    public class SecretPhrase
    {
       public static void main(String[] args)
       {
           int option;
           option = 1;
           
           if(option == 1)
           {
               Easy level = new Easy();
               level.getRandom();
           }
           else if(option == 2)
           {
        	   Medium level = new Medium();
        	   level.getRandom();
           }
           else if(option == 3)
           {
               Hard level = new Hard();
               level.getRandom();
           }
                
       }
    }
    This works fine. Depending on what option the user picks, level.getRandom() will always be called for the right class :D
    Last edited by DonCash; 04-23-2008 at 04:46 PM.
    Did this post help you? Please me! :cool:

  5. #5
    danielstoner's Avatar
    danielstoner is offline Senior Member
    Join Date
    Apr 2008
    Location
    Canada
    Posts
    191
    Rep Power
    7

    Default

    Sure there is a method. Make your Easy, Medium, Hard classes implement the same interface (say Level) or extend the same base class (say AbstractLevel). Then you can declare a Level variable outside the if statement and instantiate it to the specific instance you need inside the if.
    Daniel @ [www.littletutorials.com]
    Language is froth on the surface of thought

  6. #6
    danielstoner's Avatar
    danielstoner is offline Senior Member
    Join Date
    Apr 2008
    Location
    Canada
    Posts
    191
    Rep Power
    7

    Default

    Ok, here is the code example. I wanted to get lazy but what the heck ;-)

    Java Code:
    public interface Level
    {
        public void getRandom();
    }
    
    public class Easy implements Level
    {
        public void getRandom()
        {
            ...;
        }
    }
    public class Medium implements Level
    {
        public void getRandom()
        {
            ...;
        }
    }
    
    public class Hard implements Level
    {
        public void getRandom()
        {
            ...;
        }
    }
    
    public class SecretPhrase
    {
       public static void main(String[] args)
       {
            int option;
            option = 1;
            Level level = null;
           
           if(option == 1)
           {
               Easy level = new Easy();
           }
           else if(option == 2)
           {
        	   Medium level = new Medium();
           }
           else if(option == 3)
           {
               Hard level = new Hard();
           }
              
            if (level != null)
            { 
                level.getRandom(); 
            }
       }
    }
    Daniel @ [www.littletutorials.com]
    Language is froth on the surface of thought

  7. #7
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

  8. #8
    bobleny's Avatar
    bobleny is offline Member
    Join Date
    Apr 2008
    Posts
    50
    Rep Power
    0

    Default

    I'm still running into the same problem though. level is already defined...

    Maybe I'm doing something wrong? I created the Level interface. Then I set Easy to implement Level. Then I changed my main method like so:
    Java Code:
    public class SecretPhrase
    {
       public static void main(String[] args)
       {
           int option;
           Level level = null;
           
           option = 1;
           if(option == 1)
           {
               Easy level = new Easy();
           }
           else if(option == 2)
           {
               //Medium level = new Medium();
           }
           else if(option == 3)
           {
               //Hard level = new Hard();
           }
           
           //level.getRandom();
       }
    }
    -- www.firemelt.net --
    Cheer up, the worst has yet to come...

  9. #9
    sanjeevtarar's Avatar
    sanjeevtarar is offline Senior Member
    Join Date
    Apr 2008
    Location
    Jaipur(India)
    Posts
    318
    Rep Power
    7

    Default

    Hello,

    Try this....Hope you are looking for this

    Make a superclass say Level and define a method and then make subclasses and extends Level and override the method defined in superclass.

    Level.java

    Java Code:
    public class Level
    {
        public void getRandom()
    	{
    		System.out.println("in Level");
    	}
    }
    Easy.java

    Java Code:
    public class Easy extends Level
    {
        public void getRandom()
        {
            System.out.println("in easy");
        }
    }
    Hard.java

    Java Code:
    public class Hard extends Level
    {
        public void getRandom()
        {
            System.out.println("in hard");
        }
    }
    Medium.java

    Java Code:
    public class Medium extends Level
    {
        public void getRandom()
        {
            System.out.println("in medium");
        }
    }
    SecretPhrase.java

    Java Code:
    public class SecretPhrase 
    {
       public static void main(String[] args)
       {
            int option;
            option = 1;
            Level level = null;
           
           if(option == 1)
           {
               level = new Easy();
           }
           else if(option == 2)
           {
        	   level = new Medium();
           }
           else if(option == 3)
           {
               level = new Hard();
           }
              
            if (level != null)
            { 
                level.getRandom(); 
            }
       }
    }
    sanjeev,संजीव

  10. #10
    DonCash's Avatar
    DonCash is offline Moderator
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    240
    Rep Power
    8

    Default

    bob, did you try my method in post #4??
    Did this post help you? Please me! :cool:

  11. #11
    bobleny's Avatar
    bobleny is offline Member
    Join Date
    Apr 2008
    Posts
    50
    Rep Power
    0

    Default

    Quote Originally Posted by DonCash View Post
    bob, did you try my method in post #4??
    Actually, I didn't need to try your method. I already new it would work. The problem is, there won't be any difference between the three options other than the object. All of the methods will be called the same everything is exactly the same.

    If I do it that way I end up with the same 200 lines of code in each if statement..... I really don't want to do that.
    -------------------------------------------

    Anyways, I didn't think it necessary to do this, but take a look at my first post and there will be more information.
    -- www.firemelt.net --
    Cheer up, the worst has yet to come...

  12. #12
    danielstoner's Avatar
    danielstoner is offline Senior Member
    Join Date
    Apr 2008
    Location
    Canada
    Posts
    191
    Rep Power
    7

    Default

    Hi Bob, no actually you don't need to end with the same 200 lines of code all over the place. You can put them in a utility method and call it from all over the place :)
    Daniel @ [www.littletutorials.com]
    Language is froth on the surface of thought

  13. #13
    bobleny's Avatar
    bobleny is offline Member
    Join Date
    Apr 2008
    Posts
    50
    Rep Power
    0

    Default

    Quote Originally Posted by sanjeevtarar View Post
    Hello,

    Try this....Hope you are looking for this

    Make a superclass say Level and define a method and then make subclasses and extends Level and override the method defined in superclass.

    Level.java
    This works, however the way I have it, I need to call getRandom at Easy instead of at Level. Since level is still a Level Object, it calls Level. I need to call Easy first.
    -- www.firemelt.net --
    Cheer up, the worst has yet to come...

  14. #14
    danielstoner's Avatar
    danielstoner is offline Senior Member
    Join Date
    Apr 2008
    Location
    Canada
    Posts
    191
    Rep Power
    7

    Default

    Bob, I am sorry but I get the sensation you don't understand how OO, inheritance and polymorphism work. If Easy is derived from Level then a Level variable can point to an Easy instance and when you call methods on it it will actually call the methods of the Easy class. If you want to also execute the Level implementation of the methods you have to do it explicitly with super.
    Daniel @ [www.littletutorials.com]
    Language is froth on the surface of thought

  15. #15
    bobleny's Avatar
    bobleny is offline Member
    Join Date
    Apr 2008
    Posts
    50
    Rep Power
    0

    Default

    Quote Originally Posted by danielstoner View Post
    Bob, I am sorry but I get the sensation you don't understand how OO, inheritance and polymorphism work. If Easy is derived from Level then a Level variable can point to an Easy instance and when you call methods on it it will actually call the methods of the Easy class. If you want to also execute the Level implementation of the methods you have to do it explicitly with super.
    If your trying to say that I am new to Java and OOP, then yes, your absolutely correct!

    If you look at Easy, I am using the getRandom to pass the number of phrases in the array to Phrase. I know that in Phrase I can use Easy.phrases.length to get this same number. The problem is, when I use Easy.phrases.length to get that number, I then can't get Hard.phrases.length while using Easy.phrases.length. This means that I have to make Phrases specific to each subclass. If I have to do that, then why even have a Phrase supper class.

    You get what I'm saying?


    I also know that when:
    Phrase level = null;
    and:
    level = new Easy();
    and:
    Easy extends Phrase;

    Then when I call:
    level.getRandom();

    It looks for getRandom in Phrase, not Easy.

    ------
    Sorry, if I seem a little frustrated, but most if not all of what you guys suggested should work but isn't and I don't know what to do....


    Any other ideas?
    -- www.firemelt.net --
    Cheer up, the worst has yet to come...

  16. #16
    danielstoner's Avatar
    danielstoner is offline Senior Member
    Join Date
    Apr 2008
    Location
    Canada
    Posts
    191
    Rep Power
    7

    Default

    Ok, please send here a version of the code that compiles and I will debug and comment it for you. Because if I cannot see the actual code you are trying to run we can talk until the cow comes home ;)
    Daniel @ [www.littletutorials.com]
    Language is froth on the surface of thought

  17. #17
    bobleny's Avatar
    bobleny is offline Member
    Join Date
    Apr 2008
    Posts
    50
    Rep Power
    0

    Default

    Quote Originally Posted by danielstoner View Post
    Ok, please send here a version of the code that compiles and I will debug and comment it for you. Because if I cannot see the actual code you are trying to run we can talk until the cow comes home ;)
    Yeah, post 1 contains all needed files. Hard and Medium aren't yet in use...
    -- www.firemelt.net --
    Cheer up, the worst has yet to come...

  18. #18
    bobleny's Avatar
    bobleny is offline Member
    Join Date
    Apr 2008
    Posts
    50
    Rep Power
    0

    Default

    Quote Originally Posted by danielstoner View Post
    Hi Bob, no actually you don't need to end with the same 200 lines of code all over the place. You can put them in a utility method and call it from all over the place :)
    What do you mean by utility method? I looked online for such a thing but I couldn't find anything. Just a buch of stuff in the util package.
    -- www.firemelt.net --
    Cheer up, the worst has yet to come...

  19. #19
    danielstoner's Avatar
    danielstoner is offline Senior Member
    Join Date
    Apr 2008
    Location
    Canada
    Posts
    191
    Rep Power
    7

    Default

    Here is an implementation that works. Just implement the Medium and Hard classes. On the other hand this is not the best possible solution. In this particular case inheritance is overkill because there are no visible differences int the concepts. You could implement all this with just a class.

    Java Code:
    import java.util.Random;
    
    public abstract class Phrase
    {
        public final int getRandomIdx(int phrasesLength)
        {
            Random ran = new Random();
            return ran.nextInt(phrasesLength);
        }
    
        public abstract String getRandomPhrase();
    }
    
    public class Easy extends Phrase
    {
        private static String[] phrases = {
            "Elephant",
            "Cat",
            "Deer",
            "Rabbit",
            "Monkey",
            "Moose",
            "Crocodile",
            "Snake",
            "Goat",
            "Lion",
            "Dog",
            "Bird",
            "Mouse",
            "Bat",
            "Bear",
            "Sheep",
            "Snail",
            "Shark",
            "Frog",
            "Spider",
            "Tiger",
            "squid",
            "Octopus",
            "Worm",
            "Fish",
        };
    
        @Override
        public String getRandomPhrase()
        {
            int idx = getRandomIdx(phrases.length);
            return phrases[idx];
        }
    }
    
    public class SecretPhrase
    {
       public static void main(String[] args)
       {
           int option;
           Phrase level = null;
    
           option = 1;
           if(option == 1)
           {
               level = new Easy();
           }
           else if(option == 2)
           {
               //level = new Medium();
           }
           else if(option == 3)
           {
               //level = new Hard();
           }
    
           String phrase = level.getRandomPhrase();
           System.out.println(phrase);
       }
    }
    Daniel @ [www.littletutorials.com]
    Language is froth on the surface of thought

  20. #20
    bobleny's Avatar
    bobleny is offline Member
    Join Date
    Apr 2008
    Posts
    50
    Rep Power
    0

    Default

    Quote Originally Posted by danielstoner View Post
    Here is an implementation that works. Just implement the Medium and Hard classes. On the other hand this is not the best possible solution. In this particular case inheritance is overkill because there are no visible differences int the concepts. You could implement all this with just a class.
    You know, I tried making Phrase abstract, but I thought that when a class was abstract, the methods couldn't do things....

    Right now there isn't much to the classes, but I still have a lot more to add.

    Thanks for your help!
    -- www.firemelt.net --
    Cheer up, the worst has yet to come...

Page 1 of 2 12 LastLast

Similar Threads

  1. Creating a Comparable object
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-15-2008, 07:38 PM
  2. Need help with creating array of type object
    By riz618 in forum New To Java
    Replies: 3
    Last Post: 01-29-2008, 06:14 AM
  3. Creating a File object in Servlet
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-16-2008, 10:24 AM
  4. Creating Document object for XML parsing
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-19-2007, 04:12 PM
  5. Creating object of Type Object class
    By venkatv in forum New To Java
    Replies: 3
    Last Post: 07-17-2007, 03:33 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
  •