Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: Help with Coding School Assignment

  1. #1
    Junior Member
    Join Date
    Oct 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Help with Coding School Assignment

    I have a school project assignment and the assignment is to create a math "game" that prompts the user for their name, asks them if they want to do addition, subtraction, multiplication or division. Once they select, it picks 2 random integers between 0-10. If they get it correct, it should congratulate them, ask if they want to play again. If they get it wrong, they get 3 chances. At the end of the game when they don't want to play anymore, it is supposed to give them the total problems they did, # right, # wrong, and percentage of them getting it right. We are just learning loops and I'm probably doing something stupid for it not to work. Copying and pasting the code. Apologize for all of the comments, teacher requires them.

    import java.util.Scanner;
    import java.util.Random;
     
    public class MathGameJMB
     
    {
    	public static void main(String[] args)
    	{
    		String name;  // hold value for user's name
    		int number1;  // hold value of 1st random number
    		int number2;  // hold value of 2nd random number
    		int choice;  // hold value of menu choice chosen by user
    		int guess;  //  hold value for user's guess to math problem
    		int remainder;  // hold value for remainder for division problem
    		String again = "y"; // hold value for y/n value if user wants to keep playing
    		int attempt = 1; // hold value for the attempt number that the user is on
    		int answer = 0;  // hold value for the answer to the math problem
    		int remainderGuess; // holds value for user's guess of the remainder
    		int gamesPlayed = 0;  // Number of games the user has played
    		int answersCorrect = 0; // hold value for number of answers the user gets correct
    		int answersWrong = 0;  //hold value for number of answers the user gets wrong
    		double percentage;  // Percentage of answers the user got correct
     
    		// Create a Scanner object for keyboard input.
    		Scanner keyboard = new Scanner(System.in);
     
    		// Create a Random object to generate random numbers.
    		Random rand = new Random();
     
    		// Prompt the user to enter their name, then read the input.
    		System.out.print("Please enter your name: ");
    		name = keyboard.next();
     
    		// Echo print the user's name
    		System.out.println("Hello " + name + "!" + " Let's play a simple Math game.");
     
    		while (again.equalsIgnoreCase("y"))
    		{
    			System.out.println("1. Addition");
    			System.out.println("2. Subtraction");
    			System.out.println("3. Multiplication");
    			System.out.println("4. Division");
     
    			System.out.print("What type of problem would you like to solve? Enter your selection: ");
    			choice = keyboard.nextInt();
     
    			System.out.println("Okay, let's play! ");
     
    			// Get two random integers between 0 and 10.
    			number1 = rand.nextInt(10);
    			number2 = rand.nextInt(9);
     
    			switch (choice) {
     
    			case 1:
    				System.out.println("The problem is " + number1 + " + " + number2 + ".");
    				answer = number1 + number2; 
    				break;
     
     
    			case 2:
    				System.out.println("The problem is " + number1 + " - " + number2 + ".");
    				answer = number1 - number2; 
    				break;
     
     
    			case 3:
    				System.out.println("The problem is " + number1 + " - " + number2 + ".");
    				answer = number1 * number2; 
    				break;
     
     
    			case 4:
    				System.out.println("The problem is " + number1 + " - " + number2 + ".");
    				answer = number1 / number2; 
     
    			default:
    				System.out.println("Invalid Choice");
    			}
     
    			while (attempt  <= 3)
    			{
    				System.out.print("What is your answer? ");
    				guess = keyboard.nextInt();
     
    				if (choice == 4)
    				{
    					System.out.print("Enter the remainder: ");
    					remainder = number1 % number2;
    					remainderGuess = keyboard.nextInt();
     
    				if (guess == answer)
    				{
    					if (choice == 4 && remainder == remainderGuess)
    					{				
    						System.out.println("Congratulations! You answered correctly!");
    					}
    					System.out.println("Congratulations! You answered correctly!");
     
    				answersCorrect++;
    				gamesPlayed++;
    				}
    				else
    				{
    					System.out.println("Sorry, that answer is incorrect. Please try again.");
    					attempt++;
    				}
    			}		
    			while (attempt >3)
    			{
    				gamesPlayed++;
    				System.out.println("Study a bit more and then please try the game again. Practice makes perfect!");
    			}	
     
    			System.out.print("Would you like to play again? (Enter Y to continue and N to exit): ");
    			again = again = keyboard.next();
    		}
          }
     
    	  while (again.equalsIgnoreCase("n"))
    	  {
    		System.out.println("You played the game " + gamesPlayed + " time(s).");
    		System.out.println("You were correct " + answersCorrect + " time(s).");
    		System.out.println("You were incorrect " + answersWrong + " time(s).");
     
    		percentage = (double)answersCorrect / gamesPlayed;
    		System.out.println("You got the answer correct " + percentage + "% " + "of the time.");
    		System.out.println("Good bye " + name + " ! I hope you'll play again soon!");
    		}
       }
    }


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,147
    My Mood
    Mellow
    Thanks
    187
    Thanked 660 Times in 647 Posts

    Default Re: Help with Coding School Assignment

    Please read the Announcement topic that is at the top of each sub-forum to learn how to properly post code. That article will also give pointers on how to ask questions.

    The content of your post is actually pretty good, BUT I'm not sure what you need help with. What do you mean "not work?" Please describe which one of the many assignment requirements is not being satisfied by your code. What are the current results? How should they be different?

  3. #3
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Help with Coding School Assignment

    One way to improve you code is to start using methods. There is way too much code in your main method. Think how you can break your code done into smaller chunks and if those chunks can be moved into a separate method.
    Improving the world one idiot at a time!

  4. #4
    Junior Member
    Join Date
    Oct 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with Coding School Assignment

    Thanks for the compliment! I started testing it and here's the first problem I got to. Once I enter my name, pick addition for example then get the problem. I can enter my solution, but once I do it just goes straight to asking me if I want to play again. If I hit y, it just says "What's your answer?".

    As far as multiple methods, we haven't gotten to that yet so everything has to be like that.

  5. #5
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,147
    My Mood
    Mellow
    Thanks
    187
    Thanked 660 Times in 647 Posts

    Default Re: Help with Coding School Assignment

    You're welcome, but please fix the code so that it is posted correctly.

    As for the error you describe, many of the Scanner methods take the next token (int, double, etc.) but leave the <enter> or <lf> character entered by the user at the end of the input line, the input buffer. Then, the next Scanner method that is looking for a line of input accepts the <return> remaining in the buffer as the input. This looks to the frustrated programmer as though statements for input are being skipped.

    The way to avoid this behavior is to "flush the input buffer" by scanning for a nextLine() after those methods that leave the <enter> in the buffer and throw the result away. For example:
    // gathering numeric input
    int1 = input.nextInt();
    double1 = input.nextDouble();
     
    // clearing the input buffer
    input.nextLine();
     
    // switching to a line of data
    String continue = nextLine();

  6. #6
    Junior Member
    Join Date
    Oct 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with Coding School Assignment

    So the "input.nextLine();" segment would go after my code "guess = keyboard.nextInt();"? and after every input that the user gives? Just want to make sure I understand that correct. We haven't covered flushing the buffer yet or anything.

  7. #7
    Member Kewish's Avatar
    Join Date
    Apr 2013
    Location
    Australia
    Posts
    116
    Thanks
    10
    Thanked 17 Times in 14 Posts

    Default

    Long story short. If you are reading string data and numerical data with the Scanner class (same scanner object) you should flush the buffer right after your last numerical input. Commonly known as the Scanner Bug (while technically not a bug).

    Another work around is to have 1 scanner object for numerical input and another for Strings. I prefer to have 1 and clear the buffer.

  8. #8
    Junior Member
    Join Date
    Oct 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with Coding School Assignment

    Would that fix the error that I'm currently getting? And, I just put the flush right after the nextInt segment right?

    --- Update ---

    Hopefully this screenshot will help. Even after adding that code in, it still does the same thing.


  9. #9
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Help with Coding School Assignment

    We cannot see your screen. Post updated code.

    --- Update ---

    Looking at your original code...

    Are you asking why it does not display "congratulations" when the answer is correct? The problem is that you have that code inside the "if(choice==4)" if statement. You need to indent your code correctly.
    Improving the world one idiot at a time!

  10. #10
    Junior Member
    Join Date
    Oct 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with Coding School Assignment

    I posted my new code. The professor went over kind of an outline of how to set it up today, so this is what I've got now. The current error I'm getting when trying to compile is for the section where gamesPlayed and gamesWon are. The error is "cannot find symbol". I'm not sure if it's because they are outside of the loop or what. After that, the only thing I have to edit in, is for the remainder. I left that part out, because I'm not sure how to put it in there without messing it up.

    import java.util.Scanner;
    import java.util.Random;
     
    public class MathGameJMB
    {
    	public static void main(String[] args)
    	{
    		// Create a Scanner object for keyboard input.
    		Scanner keyboard = new Scanner(System.in);
     
    		// Create random object to generate integers
    		Random rand = new Random(); 
     
    		// Prompt the user to enter their name, then read the input.
    		System.out.print("Please enter your name: ");
    		String userName = keyboard.next();
     
    		// Echo print the user's name
    		System.out.println("Hello " + userName + "!" + " Let's play a simple Math game.");
     
    		String playAgain = "y";  // initializes variable for the user playing the game
     
    		do {
    			System.out.println("1. Addition");
    			System.out.println("2. Subtraction");
    			System.out.println("3. Multiplication");
    			System.out.println("4. Division");
     
    			System.out.print("From the choices above, what type of problem would you like to solve? Enter your selection: ");
    			int choice = keyboard.nextInt();  // initializes & reads the input for the user's choice of type of math problem
     
    			System.out.println("Okay, let's play! ");
     
    			// Get two random integers between 0 and 10. 
    			int number1 = rand.nextInt(10) + 1;
    			int number2 = rand.nextInt(10) + 1;
    			int answer;  // initialize variable for the calculated answer to the math problem
     
    			if (choice == 1) {
    				System.out.println("The problem is " + number1 + " + " + number2 + ".");
    				answer = number1 + number2; 
    			} else if (choice == 2) {
    				System.out.println("The problem is " + number1 + " - " + number2 + ".");
    				answer = number1 - number2;
    			} else if (choice == 3) {
    				System.out.println("The problem is " + number1 + " - " + number2 + ".");
    				answer = number1 * number2;
    			} else if (choice == 4) {
    				System.out.println("The problem is " + number1 + " - " + number2 + ".");
    				answer = number1 / number2;
    			}
     
    			final int MAX_TRIES = 3; // Initialize the final value for maxium numnber of tries the user gets
    			int tries = 0; // initializing variable for number of tries the user currently has
    			int gamesPlayed;  //initialize value for number of games the user has played
    			int gamesWon = 0;  // initialize the value for the number of games the user has won
     
    			System.out.print("What is your answer? ");
    			int guess = keyboard.nextInt();  // initialize the variable for the user's guess
     
    			while (tries < MAX_TRIES && guess != answer) {
    				tries++;
    				System.out.println("Sorry, that answer is incorrect. Please try again.");
    			}
     
    			if (guess == answer) {
    				System.out.println("Congratulations! You answered correctly!");
    				gamesWon++;
    				gamesPlayed++;
     
    			} else {
    				System.out.println("Study a bit more and then please try the game again. Practice makes perfect!");
    			}
    				gamesPlayed++;
     
    			System.out.print("Would you like to play again? (Enter Y to continue and N to exit): ");
    			playAgain = keyboard.next();
     
    		} while (playAgain.equals("y"));
     
    		if (playAgain.equals("n")); {
    		System.out.println("You played the game " + gamesPlayed + " time(s).");
    		System.out.println("You were correct " + gamesWon + " time(s).");
    		System.out.println("You were incorrect " + (gamesPlayed - gamesWon) + " time(s).");
     
    		percentage = (double)gamesWon / gamesPlayed;  // initialize the variable for the user's winning percentage at the game
    		System.out.println("You got the answer correct " + percentage + "% " + "of the time.");
    		System.out.println("Good bye " + userName + " ! I hope you'll play again soon!");
    		}
    	}
    }

  11. #11
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Help with Coding School Assignment

    You have declared those variables inside the do while loop and then try and access them outside the loop. You cannot do this.
    Improving the world one idiot at a time!

  12. #12
    Junior Member
    Join Date
    Oct 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with Coding School Assignment

    I got the error fixed and I'm trying to put in the remainder and prompting the user for it if they pick division, but it just skips asking for the remainder and counts it correct if the answer is correct.

    import java.util.Scanner;
    import java.util.Random;
     
    public class MathGameJMB
    {
    	public static void main(String[] args)
    	{
    		// Create a Scanner object for keyboard input.
    		Scanner keyboard = new Scanner(System.in);
     
    		// Create random object to generate integers
    		Random rand = new Random(); 
     
    		// Prompt the user to enter their name, then read the input.
    		System.out.print("Please enter your name: ");
    		String userName = keyboard.next();
     
    		// Echo print the user's name
    		System.out.println("Hello " + userName + "!" + " Let's play a simple Math game.");
     
    		String playAgain = "y";  // initializes variable for the user playing the game
    		int gamesPlayed = 0;  //initialize value for number of games the user has played
    		int gamesWon = 0;  // initialize the value for the number of games the user has won
    		int answer = 0;  // initialize variable for the calculated answer to the math problem
    		int remainder = 0;  // initialize variable for the remainder of the division problem for the user
     
    		do {
    			System.out.println("1. Addition");
    			System.out.println("2. Subtraction");
    			System.out.println("3. Multiplication");
    			System.out.println("4. Division");
     
    			System.out.print("From the choices above, what type of problem would you like to solve? Enter your selection: ");
    			int choice = keyboard.nextInt();  // initializes & reads the input for the user's choice of type of math problem
     
    			System.out.println("Okay, let's play! ");
     
    			// Get two random integers between 0 and 10. 
    			int number1 = rand.nextInt(10) + 1;
    			int number2 = rand.nextInt(10) + 1;
     
     
    			if (choice == 1) 
    			{
    				System.out.println("The problem is " + number1 + " + " + number2 + ".");
    				answer = number1 + number2; 
    			} 
    			else if (choice == 2) 
    			{
    				System.out.println("The problem is " + number1 + " - " + number2 + ".");
    				answer = number1 - number2;
    			} 
    			else if (choice == 3) 
    			{
    				System.out.println("The problem is " + number1 + " * " + number2 + ".");
    				answer = number1 * number2;
    			} 
    			else if (choice == 4) 
    			{
    				System.out.println("The problem is " + number1 + " / " + number2 + ".");
    				answer = number1 / number2;
    				choice = number1 % number2;
    			}
     
    			final int MAX_TRIES = 3; // Initialize the final value for maxium numnber of tries the user gets
    			int tries = 1; // initializing variable for number of tries the user currently has
     
    			System.out.print("What is your answer? ");
    			int guess = keyboard.nextInt();  // initialize the variable for the user's guess
    			int remainderGuess = 0;  // initialize the value and variable for the user's guess at what the remainder is
     
    			if (choice == 4)
    			{
    				System.out.print("Enter the remainder: ");
    				remainderGuess = keyboard.nextInt();
    			}
     
    			while (tries < MAX_TRIES && guess != answer || remainderGuess != remainder) {
    				tries++;
    				System.out.println("Sorry, that answer is incorrect. Please try again.");
    				System.out.print("What is your answer? ");
    				guess = keyboard.nextInt();  // record the input for the user's guess
     
    				if (choice == 4)
    				{
    					System.out.print("Enter the remainder: ");
    					remainderGuess = keyboard.nextInt();
    				}
    			}
     
    			if (guess == answer)
    			{
    				if (choice == 4 && remainderGuess == remainder)
    				{
    					System.out.println("Congratulations! You answered correctly!");
    				}
     
    				System.out.println("Congratulations! You answered correctly!");
    				gamesWon++;
    				gamesPlayed++;
    			} 
    			else
    			{
    				System.out.println("Study a bit more and then please try the game again. Practice makes perfect!");
    				gamesPlayed++;
    			}
     
     
     
    			System.out.print("Would you like to play again? (Enter Y to continue and N to exit): ");
    			playAgain = keyboard.next();
     
    		} while (playAgain.equals("y"));
     
    		// Once the user has chosen not to play the game again, output how many games they have played, times won, times lost, and winning percentage.
    		System.out.println("You played the game " + gamesPlayed + " time(s).");
    		System.out.println("You were correct " + gamesWon + " time(s).");
    		System.out.println("You were incorrect " + (gamesPlayed - gamesWon) + " time(s).");
     
    		double percentage = (double)gamesWon / gamesPlayed * 100;  // initialize the variable for the user's winning percentage at the game
    		System.out.println("You got the answer correct " + percentage + "% " + "of the time.");
    		System.out.println("Good bye " + userName + " ! I hope you'll play again soon!");
     
    		if (percentage >= 90)
    		{
    			System.out.println("You have excellent math skills!");
    		}
    		else if (percentage >= 80 && percentage < 90)
    		{
    			System.out.println("You are doing a great job, but there is room for improvement!");
    		}
    		else if (percentage < 80 && percentage >= 70)
    		{
    			System.out.println("You have average math skills.");
    		}
    		else if (percentage < 70)
    		{
    			System.out.println("You need more practice in order to improve your math skills.");
    		}
    	}
    }

  13. #13
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Help with Coding School Assignment

    Trying to add variable for remainder into my code

    Duplicate post
    Improving the world one idiot at a time!

Similar Threads

  1. Java assignment school
    By Ur Nerd in forum Paid Java Projects
    Replies: 3
    Last Post: September 7th, 2013, 03:22 AM
  2. school assignment; decimal rounding
    By ghostheadx in forum What's Wrong With My Code?
    Replies: 10
    Last Post: August 26th, 2013, 12:47 AM
  3. Problem with School Assignment.
    By SaltSlasher in forum What's Wrong With My Code?
    Replies: 11
    Last Post: February 17th, 2012, 04:12 PM
  4. School Assignment AHH!
    By Europa in forum Loops & Control Statements
    Replies: 8
    Last Post: January 20th, 2012, 08:19 AM
  5. Java program for to implement supermarket menu
    By 5723 in forum AWT / Java Swing
    Replies: 1
    Last Post: April 14th, 2009, 03:14 AM