Subscribe to The Crispy Blog        RSS Feed
-----

Learning Java Using Dream.in.Code - Random Number Game

Icon 11 Comments
I have decided to learn Java with </dream.in.code> as my only learning resource :)

So far I have managed to choose an IDE and create my first Java program.

I decided to start small and get used to the language with some simple programs. I have started with a random number guessing game and it's up to DIC to teach me how to get and display user input and also how to create random numbers.

I thought that the Java Tutorials section would be the best place to start. There are tons of tutorials in there and I found one that fit the bill Basic Java for N00blets Pt.2: Important Classes. This tutorial introduced me to the Scanner class which I would be using to get user input and also the Random class for creating random numbers, integral to this game.

I am already a C++ programmer and this probably shows in my code but here is my first Java game :)

Game.java
package javagameapp;

import java.util.Scanner;
import java.util.Random;

/**
 *
 * @author stayscrisp
 * 
 */

public class Game 
{
    Game()
    {
        m_userInput = new Scanner(System.in);
        m_randNum = new Random();
    }
    
    public void Start()
    {
        m_theNumber = m_randNum.nextInt(100);
        
        System.out.println("Welcome to the random number game!\n"
                + "Please make your first guess of a number between 0-100\n");
        
         m_theGuess = m_userInput.nextInt();  
         
         m_bIsRunning = true;
    }
    
    public boolean IsRunning()
    {
        return m_bIsRunning;
    }
    
    public void Run()
    {
        if(m_theGuess != m_theNumber)
        {
            if(m_theGuess < m_theNumber)
            {
                System.out.println("Too low, try again!\n");
                m_theGuess = m_userInput.nextInt();
            }
            else if(m_theGuess > m_theNumber)
            {
                System.out.println("Too high, try again!\n");
                m_theGuess = m_userInput.nextInt();
            }
        }
        else
        {
            System.out.println("You got it!\n");
            Start();
        }
    }
    
    private Scanner m_userInput;
    private Random  m_randNum;
    
    private int m_theNumber;
    private int m_theGuess;
    
    private boolean m_bIsRunning;
}



JavaGameApp.java

package javagameapp;

/**
 *
 * @author stayscrisp
 * 
 */

public class JavaGameApp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
        // create the game and related objects
        Game theGame = new Game();
        
        // start the game
        theGame.Start();
        
        // run until the number is guessed - call Start() if guessed
        while(theGame.IsRunning())
        {
           theGame.Run();
        }
    }
}



I think next I will attempt something a little more difficult that uses more OOP concepts. So far I have not had to use any resource outside of DIC :)

11 Comments On This Entry

Page 1 of 1

Shane Hudson Icon

27 May 2011 - 11:01 AM
A solid first attempt, and its good to see you are doing it purely using DIC!

A few questions though. I expect it is just your C++ background but how come all variables and objects are named "m_"? And how come variables are declared at the bottom of the code rather than the top? I mainly code C# but I know Java, and I can read C++.. usually they are at the top aren't they?
0

stayscrisp Icon

27 May 2011 - 11:09 AM

Shane Hudson, on 27 May 2011 - 07:01 PM, said:

usually they are at the top aren't they?


Nope, it's really up to the individual programmer. I have seen it either way and I feel it's much easier to glance at a header file and see the public methods I can use rather than private data that I can't directly use. So I choose to do it that way.

m_ is just to show that the data is a member variable, again much easier to just see the logic of the code at a glance and therefore make my life much simpler, surely you do that in C#?
1

Dogstopper Icon

27 May 2011 - 12:19 PM
That's hungarian notation...we rarely, if ever see that in Java. Also, variables and functions, with the exception of classes *should* always start in lowercase and be in CamelCase after that. That's just convention though.
0

stayscrisp Icon

27 May 2011 - 12:41 PM
hmm this will take some getting used to :P
0

bennitto Icon

27 May 2011 - 06:52 PM
My question is will the game ever end?

I see that you have a variable (isRunning) that determines whether the game repeats and I do not see its value ever being false once the game runs, or am I wrong?
0

bennitto Icon

27 May 2011 - 06:54 PM
Does the game ever end?

I do not see the isRunning variable changing to false once the game starts running. I may be wrong.
0

stayscrisp Icon

28 May 2011 - 02:06 AM
Nah, but I will update it. I coded this pretty quickly so missed a few things :)
0

Erudite Icon

30 May 2011 - 09:27 AM
I remember that it was also my first attempt when i decided to learn Java after 5 months of C language. I searched my history files and found the code. here is my implementation...


package numberfinder;

/**
 *
 * @author esergozcu
 */
import java.util.Random;
import java.util.Scanner;




public class NumberFinder {

    public static void main(String[] args) {
        
        double a;
        double randValue= Math.random();
        Random random=new Random();
        int value=random.nextInt(1);
        a = (int)(randValue*100);  
        int ax = (int)Math.round(a);
        System.out.println(ax);
        System.out.println("Please try to guess the number between 0-100\n");
        int b;
        Scanner scan = new Scanner(System.in);
        b = scan.nextInt();
        while (b != a){
            if (b > a){
                System.out.println("Please select a smaller number\n");
                b = scan.nextInt();
            }
            if (b < a){
                System.out.println("Please select a bigger number\n");
                b = scan.nextInt();
            }     
        }
        if(b == a)
            System.out.println("yes you got the number, congrulations\n");
    }
}





0

Shane Hudson Icon

31 May 2011 - 05:15 AM

stayscrisp, on 27 May 2011 - 07:09 PM, said:

Shane Hudson, on 27 May 2011 - 07:01 PM, said:

usually they are at the top aren't they?


Nope, it's really up to the individual programmer. I have seen it either way and I feel it's much easier to glance at a header file and see the public methods I can use rather than private data that I can't directly use. So I choose to do it that way.

m_ is just to show that the data is a member variable, again much easier to just see the logic of the code at a glance and therefore make my life much simpler, surely you do that in C#?



That makes sense about the public methods being at the top.

As for m_, nope I have never done it (or seen it done) in C# though of course you could do. I have never had a problem picking up anyone elses code and not being able to see the logic because of the way the variables are named. The closest to this I have seen are when variables begin with var, but never seen m_. Ah well, just goes to show how many different ways there are to code!
0

stayscrisp Icon

31 May 2011 - 09:16 AM
I have read before not to use prefixes such as m_ in C# which is probably why you have not seen it. I can't believe you haven't seen it in any C++ code though as it is extremely abundant and important. I guess it all comes down to what the standards at your job are but I was taught to do it :)
0

cfoley Icon

31 May 2011 - 04:57 PM
I can see the logic behind the m_ thing. Consider this contrived example:

class Stuff {
  int thing = 5;
  public int whatIsThing() {
    int thing = 7;
    return thing;
  }
}


Here we have two variables called [in]thing[/in], both within the same scope. There are rules that determine which one is returned... 7 in case you are wondering. [in]this.thing[/in] would return 5. But shadowing like this is something we are all taught to avoid, yet we all do. How many times have you written a method like this:

public void setX(int x) {
  this.x = x;
}


I'm not saying that it's a great use of Hungarian notation but it would get around this problem:

public void setX(int x) {
  m_x = x;
}


Actually, this is the sort of thing that gets hungarian notation a bad name. It's genuinely useful when you have variables that represent similar things in the same program. distance_miles and distance_km; x_absolute and x_screen etc...
1
Page 1 of 1

December 2014

S M T W T F S
 123456
78910111213
14151617181920
21 222324252627
28293031   

Recent Entries

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)