Results 1 to 12 of 12
  1. #1
    JohnPringle83 is offline Member
    Join Date
    May 2011
    Posts
    64
    Rep Power
    0

    Default Simple number guessing game but something's wrong???

    Hello,

    I have made a simple number guessing game, but I am getting an error and I'm not sure what is causing it.

    Here is the code and the output:

    Java Code:
    import java.util.Random;
    import java.util.Scanner;
    
    public class Main {
    	Scanner scanner = new Scanner(System.in);
    	Random rand = new Random();
    	int number;
    	int guesses;
    	int difficulty;
    		
    	public Main(){
    		startGame();
    	}
    	
    	public void startGame(){
    		System.out.println("Would you like to try and guess my number?");
    		String answer = scanner.nextLine();
    		answer = answer.toLowerCase();
    		char test = answer.charAt(0);
    		switch(test){
    		case 'y':
    			playGame();
    			break;
    		case 'n':
    			System.out.println("Game ended!");
    			System.exit(0);
    			break;
    		default:
    			System.out.println("That is not a valid response!");
    			startGame();
    			break;
    		}
    	}
    	
    	public void playGame() {
    		System.out.println("Please choose a difficilty: 1 lowest 5 highest:");
    		difficulty = scanner.nextInt();
    		number = getDifficulty(difficulty);
    		startGuessing();
    	}
    	
    	public void startGuessing(){
    		System.out.println("Please guess my number: ");
    		int guess = scanner.nextInt();
    		guesses++;
    		checkGuess(guess);
    	}
    	
    	public void playAgain(){
    		System.out.println("Would you like to play again?");
    		String answer = scanner.nextLine();
    		answer = answer.toLowerCase();
    		char test = answer.charAt(0);
    		switch(test){
    		case 'y':
    			playGame();
    			break;
    		case 'n':
    			System.out.println("Game ended!");
    			System.exit(0);
    			break;
    		default:
    			System.out.println("That is not a valid response!");
    			playAgain();
    			break;
    		}
    	}
    	
    	public int getDifficulty(int x){
    		int number = 0;
    		switch(x){
    		case 1:
    			number = 1+rand.nextInt(10);
    			System.out.println("My number is between 1 and 10 inclusive");
    			break;
    		case 2:
    			number = 1+rand.nextInt(100);
    			System.out.println("My number is between 1 and 100 inclusive");
    			break;
    		case 3:
    			number = 1+rand.nextInt(1000);
    			System.out.println("My number is between 1 and 1000 inclusive");
    			break;
    		case 4:
    			number = 1+rand.nextInt(10000);
    			System.out.println("My number is between 1 and 10000 inclusive");
    			break;
    		case 5:
    			number = 1+rand.nextInt(100000);
    			System.out.println("My number is between 1 and 100000 inclusive");
    			break;
    		default:
    			System.out.println("That is not a valid response!");
    			playGame();
    			break;
    		}
    		return number;
    	}
    	
    	public void checkGuess(int x){
    		if(number==x){
    			System.out.println("That is the correct number");
    			int score = difficulty*100/guesses;
    			System.out.println("Your score is: "+score);
    			playAgain();
    		}else{
    			if(number>x){
    				System.out.println("That number is to low!");
    				startGuessing();
    			}else if(number<x){
    				System.out.println("That number is to high!");
    				startGuessing();
    			}
    		}
    	}
    	
    	public static void main(String[] args){
    		Main main = new Main();
    	}
    }
    Java Code:
    Would you like to try and guess my number?
    y
    Please choose a difficilty: 1 lowest 5 highest:
    2
    My number is between 1 and 100 inclusive
    Please guess my number: 
    50
    That number is to high!
    Please guess my number: 
    25
    That number is to low!
    Please guess my number: 
    35
    That number is to high!
    Please guess my number: 
    30
    That is the correct number
    Your score is: 50
    Would you like to play again?
    [COLOR="red"]Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    	at java.lang.String.charAt(String.java:694)
    	at Main.playAgain(Main.java:53)
    	at Main.checkGuess(Main.java:105)
    	at Main.startGuessing(Main.java:46)
    	at Main.checkGuess(Main.java:112)
    	at Main.startGuessing(Main.java:46)
    	at Main.checkGuess(Main.java:109)
    	at Main.startGuessing(Main.java:46)
    	at Main.checkGuess(Main.java:112)
    	at Main.startGuessing(Main.java:46)
    	at Main.playGame(Main.java:39)
    	at Main.startGame(Main.java:22)
    	at Main.<init>(Main.java:12)
    	at Main.main(Main.java:118)[/COLOR]

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default

    Possibly something stuck in the scanner buffer.
    Try a nextLine() call prior to asking the play again question.

    I will say that you are burying yourself in a stack there. Each game will get deeper and deeper. I wouldn't expect a Stack Overflow, but it doesn't look right.
    Your new game should occur at the top, back up in playGame() possibly, maybe even all the way back up to main().

  3. #3
    JohnPringle83 is offline Member
    Join Date
    May 2011
    Posts
    64
    Rep Power
    0

    Default

    I see what you mean. I hadn't really noticed that the way I've been programming, that I'm building up a stack. Would calling methods that returned values be a better way of programming and then testing to see what was returned in a main method that contains the entire program flow? I'm still very new to programming but I know I'm getting there. I've been teaching myself about 3 months now and recently things are starting to fall into place.

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default

    Your code layout is very good.
    Nice small methods.
    I think you could probably do it with a loop and returning a boolean from one of the methods.
    The problem essentially lies in startGuess() calling checkGuess() which then calls startGuess() again. If checkGuess returned something then startGuess could simply loop round until checkGuess was true. Then it could ask playAgain(), which would return a boolean as well probably.

  5. #5
    JohnPringle83 is offline Member
    Join Date
    May 2011
    Posts
    64
    Rep Power
    0

    Default

    hello again, after learning more about the language i decided to re write this from scratch. Can you tell me if this is better than the last time or whether I am still going to build up a huge stack. In my startGuessing() method I have created a new NumberGuessingGame object which I am hoping will overwrite and remove the previous one that I had. I know that it won't overwrite the original that was called in my main method, but will it overwrite the one that is created ever since that one? I hope that makes sense.

    Here's the code:

    Java Code:
    import java.util.InputMismatchException;
    import java.util.Scanner;
    import java.util.Random;
    
    
    public class NumberGuessingGame {
    	int computersNumber = 0;
    	
    	public NumberGuessingGame(){
    		start();
    		getDifficulty();
    		startGuessing();
    	}
    	
    	void start(){
    		while(true){
    			System.out.println("Would you like to play?");
    			Scanner scnr = new Scanner(System.in);
    			String answer = scnr.nextLine();
    			answer = answer.toLowerCase();
    			char[] test = answer.toCharArray();
    			switch(test[0]){
    			case 'y':
    				return;
    			case 'n':
    				System.out.println("Game exited");
    				System.exit(0);
    			default:
    				System.out.println("That was not a valid input!");
    				break;
    			}
    		}
    	}
    	
    	void getDifficulty(){
    		while(true){
    			System.out.println("Choose a difficuty setting:\n1 = 1 to 10\n2 = 1 to 100\n3 = 1 to 1000");
    			Scanner scnr = new Scanner(System.in);
    			try {
    				int answer = scnr.nextInt();
    				switch(answer){
    				case 1:
    				case 2:
    				case 3:
    					Random rand = new Random();
    					computersNumber = 1+rand.nextInt(answer*10);
    					return;
    				default:
    					System.out.println("That was not a valid input!");
    					break;
    				}
    			}catch(InputMismatchException ime){
    				System.out.println("That's not a valid number! What you trying to do? break me?");
    			}
    		}
    	}
    	
    	void startGuessing(){
    		int numberOfGuesses = 0;
    		while(true){
    			System.out.println("Guess my number:");
    			Scanner scnr = new Scanner(System.in);
    			try{
    				int guess = scnr.nextInt();
    				numberOfGuesses++;
    				if(guess==computersNumber){
    					System.out.println("You got it!");
    					if(numberOfGuesses==1){
    						System.out.println("It took you "+numberOfGuesses+" try.");
    					}else{
    						System.out.println("It took you "+numberOfGuesses+" tries");
    					}
    					NumberGuessingGame ngg = new NumberGuessingGame();
    				}else if(guess>computersNumber){
    					System.out.println("Your guess was too high!");
    				}else if(guess<computersNumber){
    					System.out.println("Your guess was too low!");
    				}
    			}catch(InputMismatchException nfe){
    				System.out.println("That's not a valid number! What you trying to do? break me?");
    			}
    		}
    	}
    	
    	public static void main(String[] args){
    		new NumberGuessingGame();
    	}	
    }

  6. #6
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,445
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by JohnPringle83 View Post
    hello again, after learning more about the language i decided to re write this from scratch. Can you tell me if this is better than the last time or whether I am still going to build up a huge stack. In my startGuessing() method I have created a new NumberGuessingGame object which I am hoping will overwrite and remove the previous one that I had. I know that it won't overwrite the original that was called in my main method, but will it overwrite the one that is created ever since that one? I hope that makes sense.
    Much better but you're still building up a stack because you create a new NumberGuessingGame object when the user has guessed correctly. Why not make the constructor of that object run like this?

    Java Code:
    	
    	public NumberGuessingGame(){
    		computersNumber = 0;
    		while (true) { // keep playing
    			start();
    			getDifficulty();
    			startGuessing();
    		}
    	}
    	...
    }
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  7. #7
    JohnPringle83 is offline Member
    Join Date
    May 2011
    Posts
    64
    Rep Power
    0

    Default

    Brilliant, thanks, you'd think I would have thought of doing that considering the structure of my methods. Anyway, rep++; for that one.

  8. #8
    JohnPringle83 is offline Member
    Join Date
    May 2011
    Posts
    64
    Rep Power
    0

    Default

    Actually it wouldn't let me but I'll make a note and when I've rep++; on other people who help me, I'll come back and rep++; you

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by JohnPringle83 View Post
    Actually it wouldn't let me
    Why wouldn't it let you? Are you getting an error? If so, please post the new code and the exact error message.

  10. #10
    JohnPringle83 is offline Member
    Join Date
    May 2011
    Posts
    64
    Rep Power
    0

    Default

    I mean it wouldn't let me add rep to josAH, there's no problem with the code

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by JohnPringle83 View Post
    I mean it wouldn't let me add rep to josAH, there's no problem with the code
    Don't rep him, you'll only encourage him. ;)

  12. #12
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,445
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by JohnPringle83 View Post
    I mean it wouldn't let me add rep to josAH, there's no problem with the code
    Never mind those rep points, your eternal gratitude (and a few crates of Dutch beer and a couple of pouches of black Dutch tobacco) is enough ;-)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Reverse Number guessing game
    By rarman555 in forum New To Java
    Replies: 6
    Last Post: 04-24-2011, 01:46 AM
  2. Guessing Game
    By rose in forum Java Gaming
    Replies: 4
    Last Post: 10-27-2010, 08:00 PM
  3. Java - number guessing game
    By kev670 in forum Java Applets
    Replies: 3
    Last Post: 10-22-2010, 12:55 AM
  4. Replies: 0
    Last Post: 10-13-2010, 06:26 PM
  5. guessing game using GUI
    By yasmin k in forum New To Java
    Replies: 1
    Last Post: 10-26-2009, 12:13 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
  •