Go Back   Computer Forums > General Computing > Programming
Click Here to Login
Join Computer forums Today


Reply
 
Thread Tools Search this Thread Display Modes
 
Old 07-18-2013, 08:20 AM   #1
Baseband Member
 
Join Date: Apr 2012
Location: UK
Posts: 78
Post My first Java program.

Hi guys,
I have been learning Java, and I have just coded my first program from scratch.
It is a number guessing game. I am looking for some feedback on my code, like if it could be made simpler etc. so that I don't get into any bad practices.

Code:
//Import random and scanner
import java.util.Random;
import java.util.Scanner;


public class numberguess{
	
	public static void main(String[] args){
		
		//Declare the objects and variables
		Scanner sc = new Scanner(System.in);
		Random rdm = new Random();
		int guess = 0;
		int score = 100;
    
		//Display intro
		System.out.println("Welcome to Number Guess!");
		System.out.println("A number will be randomly generated (1-100) and your job is to guess it.");
		System.out.println("When you enter a guess you will either be told whether the number is bigger, smaller or if you guessed it.");
		System.out.println("You will receive a score at the end.");
		System.out.println("Good luck!");
		
		//Generate number
		int number = rdm.nextInt(100);
		
		//Ask for input [Before while loop in case the default value of guess is the correct answer]
		System.out.print("\nPlease enter your first guess: ");
		guess = sc.nextInt();
		score = checkGuess(guess, number, score);
    
		while (guess != number){
			//Ask for input
			System.out.print("\nPlease enter your guess: ");
			guess = sc.nextInt();
			score = checkGuess(guess, number, score);
			
		}
    
		//Display score
		System.out.println("Your score is: " + score);
		pause();
		
	}

	private static int checkGuess(int guess, int number, int score){
		//Compare guess to number and display the appropriate message. Keep track of score.
		if (guess == number) {
			System.out.println("\nYou have guessed the number!");
		}
		else if (guess < number) {
			System.out.println("The number is bigger.");
			score -= 3;
		}
		else {
			System.out.println("The number is smaller.");
			score -= 3;
		}
	return score;
	}
  
	private static void pause() {
		System.out.println("\nPress enter to exit...");
		Scanner sc = new Scanner(System.in);
		sc.nextLine();
	}
}
Thanks.
__________________

__________________
CPU - AMD Athlon II X3 450, MB - Asus M5A78L-M LX, GPU - EVGA GTX 660 Ti, RAM - 8GB Ballistix 1333Mhz, PSU - 600W OCZ Modxstream-Pro
ParalizedTime is offline   Reply With Quote
Old 07-18-2013, 08:23 AM   #2
Golden Master
 
BK_123's Avatar
 
Join Date: Dec 2009
Location: Australia
Posts: 7,529
Default Re: My first Java program.

Is the program itself ready yet to be tested?
__________________

BK_123 is online now   Reply With Quote
Old 07-18-2013, 08:30 AM   #3
Baseband Member
 
Join Date: Apr 2012
Location: UK
Posts: 78
Default Re: My first Java program.

The code is in my original post, and I have already tested it (it works), I am just look for feedback on the code itself, for example if there is a simpler way to do anything. This is so that I don't get into doing things a more complicated way in the future if there is an easier way.
__________________
CPU - AMD Athlon II X3 450, MB - Asus M5A78L-M LX, GPU - EVGA GTX 660 Ti, RAM - 8GB Ballistix 1333Mhz, PSU - 600W OCZ Modxstream-Pro
ParalizedTime is offline   Reply With Quote
Old 07-18-2013, 08:41 AM   #4
Fully Optimized
 
strollin's Avatar
 
Join Date: Mar 2011
Location: USA
Posts: 1,941
Default Re: My first Java program.

I don't see a way for the user to exit from the game at any time except at the end. What if the user wishes to exit sooner?
strollin is offline   Reply With Quote
Old 07-18-2013, 08:55 AM   #5
Baseband Member
 
Join Date: Apr 2012
Location: UK
Posts: 78
Default Re: My first Java program.

The game runs in a console, so they just close the console window?

---------- Post added at 01:55 PM ---------- Previous post was at 01:50 PM ----------

However if I want the person to be able to exit the game without closing the console I should just be able to add an extra if statement in the checkGuess method which will detect if the user has typed 'exit' and then terminate the application.
__________________
CPU - AMD Athlon II X3 450, MB - Asus M5A78L-M LX, GPU - EVGA GTX 660 Ti, RAM - 8GB Ballistix 1333Mhz, PSU - 600W OCZ Modxstream-Pro
ParalizedTime is offline   Reply With Quote
Old 07-18-2013, 09:02 AM   #6
Baseband Member
 
Join Date: Apr 2012
Location: UK
Posts: 78
Default Re: My first Java program.

Done, if the player enters 111 as their guess, the application will be terminated. - Added a message informing the player in the intro.

New checkGuess method:
Code:
private static int checkGuess(int guess, int number, int score){
		//Compare guess to number and display the appropriate message. Keep track of score. Check if player want to quit.
		if (guess == 111) {
			System.exit(0);
		}
		else if (guess == number) {
			System.out.println("\nYou have guessed the number!");
		}
		else if (guess < number) {
			System.out.println("The number is bigger.");
			score -= 3;
		}
		else {
			System.out.println("The number is smaller.");
			score -= 3;
		}
	return score;
	}


---------- Post added at 02:02 PM ---------- Previous post was at 02:01 PM ----------

If you are wondering, it is a number because the scanner only checks for intigers.
Any other problems?
__________________
CPU - AMD Athlon II X3 450, MB - Asus M5A78L-M LX, GPU - EVGA GTX 660 Ti, RAM - 8GB Ballistix 1333Mhz, PSU - 600W OCZ Modxstream-Pro
ParalizedTime is offline   Reply With Quote
Old 07-18-2013, 10:00 AM   #7
Fully Optimized
 
strollin's Avatar
 
Join Date: Mar 2011
Location: USA
Posts: 1,941
Default Re: My first Java program.

Quote:
Originally Posted by ParalizedTime View Post
The game runs in a console, so they just close the console window?

---------- Post added at 01:55 PM ---------- Previous post was at 01:50 PM ----------

However if I want the person to be able to exit the game without closing the console I should just be able to add an extra if statement in the checkGuess method which will detect if the user has typed 'exit' and then terminate the application.
With this simple game, yes, the person could simply close the console. But you were saying that you wanted to learn to do things right and not get into bad habits.

There are other things you could add to make the game more robust. How about an option to start the game over? What happens if someone enters a letter or some other random character other than a number? What happens if someone enters 87.325? What happens if a person enters a large number like 128299412? It is dangerous to have your input expect to be a nice, simple integer because users might enter anything at the prompt.

One way to handle things would be to accept the input as a string, verify that it only contains a valid integer, then convert from string to int.
strollin is offline   Reply With Quote
Old 07-18-2013, 11:24 AM   #8
Baseband Member
 
Join Date: Apr 2012
Location: UK
Posts: 78
Default Re: My first Java program.

Thanks, I am going to work on detecting the input is correct now.
__________________
CPU - AMD Athlon II X3 450, MB - Asus M5A78L-M LX, GPU - EVGA GTX 660 Ti, RAM - 8GB Ballistix 1333Mhz, PSU - 600W OCZ Modxstream-Pro
ParalizedTime is offline   Reply With Quote
Old 07-18-2013, 12:16 PM   #9
Baseband Member
 
Join Date: Apr 2012
Location: UK
Posts: 78
Default Re: My first Java program.

It now check whether the input is an integer, if it is not is says "Invalid input."!

Now all I have to do is add the option to restart the game.
__________________
CPU - AMD Athlon II X3 450, MB - Asus M5A78L-M LX, GPU - EVGA GTX 660 Ti, RAM - 8GB Ballistix 1333Mhz, PSU - 600W OCZ Modxstream-Pro
ParalizedTime is offline   Reply With Quote
Old 07-18-2013, 06:24 PM   #10
Site Team
 
celegorm's Avatar
 
Join Date: Sep 2006
Posts: 10,713
Send a message via AIM to celegorm
Default Re: My first Java program.

Quote:
Originally Posted by strollin View Post
What happens if someone enters a letter or some other random character other than a number? What happens if someone enters 87.325? What happens if a person enters a large number like 128299412? It is dangerous to have your input expect to be a nice, simple integer because users might enter anything at the prompt
You're already working on this by the sounds of it, but I wanted to stress Strollin's point here. The hardest part of writing good software in my opinion and experience is thinking of all the ways the user can mess up the way they are supposed to give your program data. I've found it's always best to assume the data entered will be invalid until proven valid.

While it might be a little over zealous, I've also kept to that habit when working with things like number fields that are designed to force the user to enter only valid characters. My reasoning behind this is that you never know if an updated java version released down the road will break the number field's control or maybe there'd be some incompatibility that'd keep it from working properly. You never should assume third party utilities and controls will always function as promised or expected when they are giving you data.
__________________

__________________
"as a fanboy i refuse to admit it and will pull countless things out of my butt to disprove it"

Team Thelegorm! Total Kills: 21 (i iz in uor profile, editsing your sigz)
celegorm is offline   Reply With Quote
Reply

Tags
first program, java

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off



All times are GMT -5. The time now is 08:25 AM.


Powered by vBulletin® Version 3.8.8 Beta 4
Copyright ©2000 - 2017, vBulletin Solutions, Inc.
Search Engine Friendly URLs by vBSEO 3.6.0