Results 1 to 13 of 13

Thread: more java questions.     submit to reddit submit to twitter

  1. #1
    Cerberus
    Join Date
    Oct 2008
    Posts
    436
    BG Level
    4

    more java questions.

    Ok i have to do a simple coin flip program. I have it made and working:

    Code:
    import java.util.Random;
    
    public class Coin {
    
    	public static void main(String[] args) { 
    		int heads = 0;
    		int tails = 0;
    		for(int i = 0; i< 1000; i++) {
    			if(Math.random() < 0.5) { heads = heads +1; }
    			else { tails = tails +1; }
    		}
    		
    		System.out.println("heads:" + heads + "");
    		System.out.println("tails:" + tails + "");
    	}
    }
    problem is that the professor wants us to use a class with these methods

    Code:
    void flip(): flips the coin 
    boolean isHeads(): returns true if the coin shows heads
    String toString(): returns the current face of the coin as a string
    I suck at using functions can anyone help me out and show me how to do it the way hes wanting?

    I'm totaly lost on that part

  2. #2
    i'm awesome.
    Join Date
    May 2005
    Posts
    9,218
    BG Level
    8

    You don't suck at fucntions, your main method looks fine! Look at your main method, just like any other method, it is simple a namespace which references a set of actions which belongs to the class Coin. Can you locate and isolate the 'flip' action in your code?

    Consider your Coin class, how would a method like 'isHeads' be used, does it require you to rethink the structure of your class? What sort of instance variables might you need in order to solve the problem efficiently. Can you rethink the problem entirely? (This is largely dependent on what your professor wants and what he's trying to teach you with this assignment). Similarly, consider how you might use 'toString'? Basically, does your class represent a single coin, many coins, facilitate working with a set of coins, etc.? You need to understand your problem and map it to a object with actions, this is most likely what your professor is driving at.

    Answer these questions, elaborate on your assignment with your understanding of it and I'm sure if I don't, someone else can help you think your way through it. Look at your notes, look at the problem, think it through! One of the best feelings when programming is discovering a solution on your own, struggle and find the answer and you will feel an immense gratification.

    P.S. I'm going to sleep because I just got home from drinking and I gotta wake up early tomorrow. If you are in this course trying to make a career out of programming though, I would actually suggest you not seek help for assignments. Part of your growth as a programmer is having the motivation to find a solution on your own and not needing a hand hold. The best way to cheapen your experience and illegitimize your education is to not allow yourself to struggle when you hit a road block. I know it sounds cliche but you will learn so much by being at a brick wall and banging your head against it, again look at your notes/book and the answer will seem obvious as you familiarize yourself with the concepts.

  3. #3
    Melee Summoner
    Join Date
    Jan 2011
    Posts
    37
    BG Level
    1
    FFXI Server
    Alexander

    Does the professor want the methods in a separate class where you will call them in the client class?

    For more information on creating methods in a class you might want to check out h ttp://download.oracle.com/javase/tutorial/java/javaOO/methods.html

    Going to sleep now but will help in the morning if you are still stuck

  4. #4
    Chram
    Join Date
    Aug 2007
    Posts
    2,699
    BG Level
    7
    FFXIV Character
    Nours Sruon
    FFXIV Server
    Moogle
    FFXI Server
    Fenrir

    random tip: variable++ is the same as variable = variable + 1
    as for the functions, you just need to realize the flow of your program, put it on paper if needed, it's much easier than looking blindly.

  5. #5
    i'm awesome.
    Join Date
    May 2005
    Posts
    9,218
    BG Level
    8

    I would only recomment shortening it to variable+=1

    Postfix/Prefix operators have a specific purpose of incrementing before/after reading the value from memory for use so they shouldn't be used to simply increment unless you understand the concept. An ignorant user could use it incorrectly and have significant trouble trying to debug the code.

  6. #6
    Banned.

    Join Date
    Jul 2005
    Posts
    5,821
    BG Level
    8
    FFXI Server
    Sylph
    WoW Realm
    Arthas

    Do what everyone else said or the solved program is in the spoiler. Do you have the self control to not cheat? HMMMMM..



    Spoiler: show

    I havent tested this and its mostly pseudo code.. I havent used Java is awhile so it might not work.
    Code:
    import java.util.Random;
    
    public class Coin {
        int heads = 0;
        int tails = 0;
    
        public static void main(String[] args) {
        
            FlipCoin flip = new FlipCoin();
    
            for(int i = 0; i< 1000; i++) {
                flip.flip();           
                if(flip.isHeads() == true){ heads++; } else { tails++; }
                System.out.println("Flip: " + i + " : " + flip.toString());
            }        
            
            System.out.println("heads:" + heads + "");
            System.out.println("tails:" + tails + "");
        }
    }
    
    public class FlipCoin 
    {
        bool boolCoin = false;
        
        public FlipCoin(){}
        
        public void flip()
        {
            if(Math.random() < 0.5) { boolCoin = true;} else { boolCoin = false; }
        }
        
        bool isHeads()
        {
            return boolCoin;
        }
        
        String toString()
        {
            if(boolCoin == false){ return "Heads"; } else { return "Tails"; }
        }
    }
    
    
    //void flip(): flips the coin
    //boolean isHeads(): returns true if the coin shows heads
    //String toString(): returns the current face of the coin as a string

  7. #7
    Nidhogg
    Join Date
    Oct 2005
    Posts
    3,612
    BG Level
    7
    FFXIV Character
    Glick Wick
    FFXIV Server
    Ultros
    FFXI Server
    Bahamut

    Quote Originally Posted by Maguspk View Post
    I would only recomment shortening it to variable+=1

    Postfix/Prefix operators have a specific purpose of incrementing before/after reading the value from memory for use so they shouldn't be used to simply increment unless you understand the concept. An ignorant user could use it incorrectly and have significant trouble trying to debug the code.
    You will not have trouble debugging when using prefix/postfix operators to increment in any managed language.

  8. #8
    Cerberus
    Join Date
    Oct 2008
    Posts
    436
    BG Level
    4

    Yes i can resist. But i did use the code to help me out (didn't copy it just used as reference)

    But new question. I have to prompt user to enter what kind of dice they want to use. then random the number and return it. Must also use:

    * int roll(): sets (and returns) the face value to a uniform random number between 1 and the number of faces

    * int getFaceValue(): returns the current face value of the die

    * String toString(): returns the string representation of the face value

    Lots of errors, but using the posted code tried to figure it out.

    Code:
    import java.util.Random;
    
    public class Die {
    
        public static void main(String[] args) {
    		
    		System.out.println("Which dice would you like to use? 4, 6, 8, 10, 12, 20, and 100:");
    		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    		int anwser = 0;
    		
    		try {
    			anwser = br.readLine();
    		} 
    		
    		catch (IOException ioe) {
            System.out.println("IO error trying to read your Die");
            System.exit(1);
          }
    
    	
    		RollDic roll = new RollDic();
            roll.roll();       
            System.out.println("Your Roll resulted in an:" + randomNum + "");
        }
    }
    
    public class RollDie {
    	int result = 0;
        	
        public RollDie(){}
    	
        public int roll() {
    		Random generator = new Random();
            int randomNum = generator.nextInt(anwser + 1);
    		result = randomNum;
        }
        
        public int GetFaceValue() {
            return result;
        }
    }
    Editing as i fix errosr

  9. #9
    E. Body
    Join Date
    Jan 2007
    Posts
    2,103
    BG Level
    7

    You have no return value for roll(), but it is supposed to return an int. I'm assuming you want that to return void instead, as result is a private member variable.

    Also for the function GetFaceValue, the Java convention is to name getters and setters after their private member variable. So to make things more clear, either change result to faceValue or name the function getResult, with the first word of the function lower case.

    Also make result, or whatever you name it to, private.

    And Java doesn't require default constructors if you don't want them to do anything different, it doesn't even need to be specified (and you shouldn't be, actually).

  10. #10
    Melee Summoner
    Join Date
    Jan 2011
    Posts
    37
    BG Level
    1
    FFXI Server
    Alexander

    Code:
    		RollDic roll = new RollDic();
    I noticed that your class is declared as RollDice but you put RollDic. It will just give you errors if you leave off the "e"

    Edit:

    Do you need to use BufferedReader? I have always found that for simple inputs the scanner class is much easier to understand. For example...

    Spoiler: show
    Code:
    import java.util.Scanner; //import the Scanner class.
    public class Die {
        public static void main(String[] args) {
    		Scanner keyboard = new Scanner(System.in);
    		System.out.println("Which dice would you like to use? 4, 6, 8, 10, 12, 20, and 100:");
    		int anwser = keyboard.nextInt();
                    keyboard.nextLine();
    I haven't really used the BufferedReader class so I am used to Scanner. You can use either.


  11. #11
    Banned.

    Join Date
    Jul 2005
    Posts
    5,821
    BG Level
    8
    FFXI Server
    Sylph
    WoW Realm
    Arthas

    Just wondering, what compiler are you using? Usually most compilers point out small things in code like that in real time.

  12. #12
    Chram
    Join Date
    Nov 2007
    Posts
    2,662
    BG Level
    7
    FFXIV Character
    Avelle Asteria
    FFXIV Server
    Hyperion
    FFXI Server
    Phoenix
    WoW Realm
    Alleria

    I remember my Java class years ago using the command line to compile everything, but these days there's really no reason not to use something like Eclipse. It's still not as good as Visual Studio imo, but it's a damn far cry from using the command line! It even has intellisense!

  13. #13
    :3
    Join Date
    Nov 2006
    Posts
    653
    BG Level
    5

    Eclipse is an awesome IDE for java. It tells you everything that is wrong with your code. Even before the compile.

Similar Threads

  1. more java code
    By Skie in forum Tech
    Replies: 0
    Last Post: 2010-09-24, 20:14