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, 07: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, 07:23 AM   #2
Golden Master
 
BK_123's Avatar
 
Join Date: Dec 2009
Location: Australia
Posts: 7,556
Default Re: My first Java program.

Is the program itself ready yet to be tested?
__________________

__________________
BK_123 is offline   Reply With Quote
Old 07-18-2013, 07: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, 07:41 AM   #4
Fully Optimized
 
strollin's Avatar
 
Join Date: Mar 2011
Location: USA
Posts: 2,617
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, 07: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, 08: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, 09:00 AM   #7
Fully Optimized
 
strollin's Avatar
 
Join Date: Mar 2011
Location: USA
Posts: 2,617
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, 10: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, 11:16 AM   #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, 05:24 PM   #10
Site Team
 
celegorm's Avatar
 
Join Date: Sep 2006
Posts: 10,720
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
Old 07-20-2013, 03:59 PM   #11
Site Team
 
berry120's Avatar
 
Join Date: Jul 2009
Location: England, UK
Posts: 3,434
Default Re: My first Java program.

The improvements everyone has suggested thus far are good, and I'd echo celegorm's point about not expecting user input to be sanitised - some very famous and expensive programming mistakes have happened this way, and no doubt many more will happen in the future. I'm not sure I'd go as far as to do the same thing for, say, UI controls that can only accept numbers - I haven't known a version of Java that broke something that fundamental, and I'd argue that the excess code here harms readability more than the benefit you'd gain in such a corner case. But I agree with the principle, and functionally at least it can't do any harm to double check.

Where I will chime in is on style - overall it's not bad, but just a few points that I think are worth mentioning:
  • Inline Comments - You've got a lot of comments in your code like "//print message" and so on. Look at any piece of code written by a beginner and they'll almost always put these in, look at any piece of code written by a professional, and apart from in odd corner cases, you won't find any. That's because too many comments in the wrong places can actually *hurt* readability of the code. If you feel that you must comment something this way, then you should really break it up into separate methods and use:
  • Javadoc comments. These are what professionals *do* use, and I rarely see beginners use these - but they're what are often required in a professional setting. The javadoc tool takes these and generates the code documentation for you, so they're what people actually look at. Pretty much every method you write should be commented this way, in this format - they start "/**" and end "*/". See here for details - worth taking this on board
  • Indentation - it's pretty good, but there's a couple of cases (such as in your last return statement) where it doesn't quite line up. Get this right early on, otherwise when you're staring at complex code later it's really going to haunt you if you can't read through its flow simply.
  • Java is an OO language by nature, and while many people start just using static methods as defined here try not to go too far down this road before you start looking at objects. When you understand them then most coding should be done via objects, not static methods - all the main method should really do is instantiate an object or two and perhaps call a method or two on them. The rest should be handled in non-static code. (Just something to bear in mind for the future.)
__________________
Save the whales, feed the hungry, free the mallocs.
berry120 is offline   Reply With Quote
Old 07-21-2013, 03:00 AM   #12
Baseband Member
 
Join Date: Apr 2012
Location: UK
Posts: 78
Default

Thanks for all your feedback guys! I am going to reasearch some more, I will keep everything you have said in mind in my next project. Thanks again
__________________
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-29-2013, 04:26 PM   #13
Beta Member
 
the prince's Avatar
 
Join Date: Jul 2013
Location: usa
Posts: 1
Default Re: My first Java program.

good work go man....!
__________________

__________________
the prince 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 06:26 PM.


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