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 12 of 12

Thread: Random maths operator generation

  1. #1
    Junior Member
    Join Date
    Apr 2013
    Location
    United Kingdom
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Random maths operator generation

    Good evening.

    I am writing a program which allows the user to input their name and then answer ten questions that take the form "1 + 2 = ?", where the ? is, of course, the answer to be given. The numbers and operator - add or subtract - are to be generated at random. I have almost completed the program, but the real stumbling block right now is knowing what to do for the random operator; I have tried using a switch statement, but that didn't work for some reason (although whether I did it right or not is another matter entirely), and I don't know what else to try.

    Below is what I've done so far:

    import java.util.Scanner;
    import java.util.Random;
     
    public class MathsQuestions {
    	public static void main(String[] args) {
    		Scanner scan = new Scanner(System.in);
    		String user;
     
    		System.out.print("What is your name? ");
    		user = scan.nextLine();
    		System.out.println("Hello " + user + ", let's begin.");
    		playGame();
    		System.out.println("Thank you for playing; hope to see you again soon!");
    	}
     
    	public static void playGame() {
    		Random rand = new Random();
    		Scanner answer = new Scanner(System.in);
    		int count = 1;
    		int score = 0;
    		int firstNumber = rand.nextInt(8) + 11;
    		int secondNumber = rand.nextInt(9) + 1;
    		int userAnswer;
    		char operator = rand.nextBoolean() ? '+' : '-';
     
    		while(count <= 10) {
    			System.out.print(count + ".   " + firstNumber + operator + secondNumber + " = ");
    			userAnswer = answer.nextInt();
    			if (userAnswer == rightAnswer) {
    				System.out.println("Correct!");
    				count++;
    				score++;
    			} else {
    				System.out.println("Incorrect - right answer is " + rightAnswer + ".");
    				count++;
    			}
    		}
     
    		if (score == 10) {
    			System.out.println("You scored " + score + " - excellent!");
    		} else if (score > 5) {
    			System.out.println("You scored " + score + " - good job.");
    		} else if (score > 1) {
    			System.out.println("You scored " + score + " - you need to try harder.");
    		} else {
    			System.out.println("You scored " + score + " - it'd be worth getting extra help.");
    		}
    	}
    }

    I would appreciate any help I can get, as this is becoming quite frustrating...

    Regards.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,265
    Thanks
    56
    Thanked 2,372 Times in 2,343 Posts

    Default Re: Random maths operator generation

    what to do for the random operator; I have tried using a switch statement, but that didn't work for some reason
    What is wrong with the posted code? What happens when it is executed? What does it do or not do correctly?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Apr 2013
    Location
    United Kingdom
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Random maths operator generation

    Quote Originally Posted by Norm View Post
    What is wrong with the posted code? What happens when it is executed? What does it do or not do correctly?
    The switch statement I tried (that is not in my code now) was as follows:

    int num = (int)(2*Math.random()+1);
    char operator;
    // ...
    switch (num) {
    	case 1: operator = '+';
    		break;
    	case 2: operator = '-';
    		break;
    }

    ...but I got three instances of the "cannot find symbol" error whenever I tried to compile the program.

    As for the code in my first post, it compiles and runs correctly but neither the numbers nor the operator change from question to question; they stay the same for all ten questions, and only change when I run the program again.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,265
    Thanks
    56
    Thanked 2,372 Times in 2,343 Posts

    Default Re: Random maths operator generation

    Can you post the contents of the error messages that show the cannot find symbol error?

    neither the numbers nor the operator change from question to question
    And the contents of the console when you execute the current program.

    How can you execute the code in post #1? It does not compile without errors.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Apr 2013
    Location
    United Kingdom
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Random maths operator generation

    Quote Originally Posted by Norm View Post
    How can you execute the code in post #1? It does not compile without errors.
    My mistake; I just remembered that it executed well if I used a single, fixed operator rather than the random operator statement (although there was still no change in the numbers)...

    The code, as it stands, is as follows:

    import java.util.Scanner;
    import java.util.Random;
     
    public class MathsQuestions {
    	public static void main(String[] args) {
    		Scanner scan = new Scanner(System.in);
    		String user;
     
    		System.out.print("What is your name? ");
    		user = scan.nextLine();
    		System.out.println("Hello " + user + ", let's begin.");
    		playGame();
    		System.out.println("Thank you for playing; hope to see you again soon!");
    	}
     
    	public static void playGame() {
    		Random rand = new Random();
    		Scanner answer = new Scanner(System.in);
    		int count = 1;
    		int score = 0;
    		int firstNumber = rand.nextInt(8) + 11;
    		int secondNumber = rand.nextInt(9) + 1;
    		int num = (int)(2*Math.random()+1);
    		int userAnswer;
                    int rightAnswer;
     
    		switch (num) {
    			case 1: operator = '+';
    					break;
    			case 2: operator = '-';
    					break;
    		}
     
    		while(count <= 10) {
    			System.out.print(count + ".   " + firstNumber + num + secondNumber + " = ");
    			userAnswer = answer.nextInt();
    			if (userAnswer == rightAnswer) {
    				System.out.println("Correct!");
    				count++;
    				score++;
    			} else {
    				System.out.println("Incorrect - right answer is " + rightAnswer + ".");
    				count++;
    			}
    		}
     
    		if (score == 10) {
    			System.out.println("You scored " + score + " - excellent!");
    		} else if (score > 5) {
    			System.out.println("You scored " + score + " - good job.");
    		} else if (score > 1) {
    			System.out.println("You scored " + score + " - you need to try harder.");
    		} else {
    			System.out.println("You scored " + score + " - it'd be worth getting extra help.");
    		}
    	}
    }

    ...and the contents of the error messages when I execute it (I'm doing this through the Command Prompt):

    MathsQuestions.java:28: error: cannot find symbol
                            case 1: operator = '+';
    symbol: variable operator
    location: class MathsQuestions
     
    MathsQuestions.java:30: error: cannot find symbol
                            case 1: operator = '-';
    symbol: variable operator
    location: class MathsQuestions

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,265
    Thanks
    56
    Thanked 2,372 Times in 2,343 Posts

    Default Re: Random maths operator generation

    The compiler can not find a definition for the symbol named in the error message. Be sure to declare/define all variables used in the program.

    no change in the numbers
    Where do the numbers get changed? Where are the contents of the numbers displayed? Are the contents of the numbers changed between the times they are shown? If the code does not change them, their contents will remain the same.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Apr 2013
    Location
    United Kingdom
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Random maths operator generation

    Quote Originally Posted by Norm View Post
    Are the contents of the numbers changed between the times they are shown? If the code does not change them, their contents will remain the same.
    The range of the first number is 11 to 19, while the range of the second number is 1 to 9. As far as I can see I have followed the syntax for declaring variables for random numbers to the tee, yet for some reason the number stays the same throughout a single execution... for example, this little piece of code (written separately, just to make sure that I have indeed gotten the syntax right):

    import java.util.Random;
     
    public class Maths {
    	public static void main(String[] args) {
    		Random random = new Random();
    		int randomNumber = random.nextInt(8)+11;
     
    		for (int count = 1; count <= 10; count++) {
    			System.out.println(randomNumber);
    		}
    	}
    }

    ...produces the following output when I run it once:

    13
    13
    13
    13
    13
    13
    13
    13
    13
    13

    ...and then this when I run it a second time:

    18
    18
    18
    18
    18
    18
    18
    18
    18
    18

    Either I'm being stupid or it's a simple case of oversight, but I just can't get my head around this one...

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,265
    Thanks
    56
    Thanked 2,372 Times in 2,343 Posts

    Default Re: Random maths operator generation

    Where is the number given a value?
    Where is the number displayed?
    Is there a loop?
    Are both of the above locations INSIDE the same loop?

    If you do not change the number's value, its value will remain the same.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Apr 2013
    Location
    United Kingdom
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Random maths operator generation

    Quote Originally Posted by Norm View Post
    Are both of the above locations INSIDE the same loop?

    If you do not change the number's value, its value will remain the same.
    And that's where I've been going wrong... I should've looked more closely.

    Okay, now I'm somewhat on the right track - the numbers and operators are changing with each question, as expected. The code is now as follows:

    import java.util.Scanner;
    import java.util.Random;
     
    public class RandomMaths {
    	public static void main(String[] args) {
    		Scanner scan = new Scanner(System.in);
    		String user;
     
    		System.out.print("What is your name? ");
    		user = scan.nextLine();
    		System.out.println("Hello " + user + ", let's begin.\n");
    		playGame();
    		System.out.println("Thank you for playing; hope to see you again soon!");
    	}
     
    	public static void playGame() {
    		Random rand = new Random();
    		Scanner answer = new Scanner(System.in);
    		int score = 0;
     
    		for(int count = 1; count <= 10; count++) {
    			int firstNumber = rand.nextInt(8) + 11;
    			int secondNumber = rand.nextInt(9) + 1;
    			int userAnswer;
    			char operator = rand.nextBoolean() ? '+' : '-';
    			int rightAnswer = firstNumber + operator + secondNumber;
     
    			System.out.print(count + ".   " + firstNumber + " " + operator + " " + secondNumber + " = ");
    			userAnswer = answer.nextInt();
    			if (userAnswer == rightAnswer) {
    				System.out.println("Correct!\n");
    				score++;
    			} else {
    				System.out.println("Incorrect - right answer is " + rightAnswer + ".\n");
    			}
    		}
     
    		if (score == 10) {
    			System.out.println("You scored " + score + " - excellent!");
    		} else if (score > 5) {
    			System.out.println("You scored " + score + " - good job.");
    		} else if (score > 1) {
    			System.out.println("You scored " + score + " - you need to try harder.");
    		} else {
    			System.out.println("You scored " + score + " - it'd be worth getting extra help.");
    		}
    	}
    }

    But the output once I start to answer the questions is still not what I'm expecting (the name input is working fine):

    1.   14 + 6 = 20
    Incorrect - right answer is 63.
     
    2.   16 - 5 = 11
    Incorrect - right answer is 66.
     
    3.   14 + 1 = 15
    Incorrect - right answer is 58.
     
    //...
     
    9.   11 + 5 = 16
    Incorrect - right answer is 59.
     
    10.   14 + 8 = 22
    Incorrect - right answer is 65.
     
    You scored 0 - it'd be worth getting extra help.
    Thank you for playing; hope to see you again soon!

    So now the problem lies in how I'm declaring the 'rightAnswer' variable.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,265
    Thanks
    56
    Thanked 2,372 Times in 2,343 Posts

    Default Re: Random maths operator generation

    A char variable has an int value and can be added to an int. The expression:
    int rightAnswer = firstNumber + operator + secondNumber;
    is adding three int values together. operator has an int value. Copy and execute this:
          System.out.println("+="+ (int)'+'); //+=43
    The expression must be coded with the correct operator when it is compiled.

    Hint: select the operator and do the math at the same time using an if else statement
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Apr 2013
    Location
    United Kingdom
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Random maths operator generation

    Okay, I've finally cracked it - I tried using a switch statement again and it's working correctly. Here's the code now:

    import java.util.Scanner;
    import java.util.Random;
     
    public class MathsQuestions {
    	public static void main(String[] args) {
    		Scanner scan = new Scanner(System.in);
    		String user;
     
    		System.out.print("What is your name? ");
    		user = scan.nextLine();
    		System.out.println("Hello " + user + ", let's begin.\n");
    		playGame();
    		System.out.println("Thank you for playing; hope to see you again soon!");
    	}
     
    	public static void playGame() {
    		Random rand = new Random();
    		Scanner answer = new Scanner(System.in);
    		int score = 0;
     
    		for(int count = 1; count <= 10; count++) {
    			int firstNumber = rand.nextInt(8) + 11;
    			int secondNumber = rand.nextInt(9) + 1;
    			int num = rand.nextInt(2) + 1;
    			char operator;
    			int userAnswer;
    			int rightAnswer;
     
    			switch (num) {
    				case 1: operator = '+';
    						break;
    				case 2: operator = '-';
    						break;
    			}			
     
    			if (num == 1) {
    				System.out.print(count + ".   " + firstNumber + " + " + secondNumber + " = ");
    				userAnswer = answer.nextInt();
    				rightAnswer = firstNumber + secondNumber;
    				if (userAnswer == rightAnswer) {
    					System.out.println("Correct!\n");
    					score++;
    				} else {
    					System.out.println("Incorrect - right answer is " + rightAnswer + ".\n");
    				}
    			} else if (num == 2) {
    				System.out.print(count + ".   " + firstNumber + " - " + secondNumber + " = ");
    				userAnswer = answer.nextInt();
    				rightAnswer = firstNumber - secondNumber;
    				if (userAnswer == rightAnswer) {
    					System.out.println("Correct!\n");
    					score++;
    				} else {
    					System.out.println("Incorrect - right answer is " + rightAnswer + ".\n");
    				}			
    			}
    		}
     
    		if (score == 10) {
    			System.out.println("You scored " + score + " - excellent!");
    		} else if (score > 5) {
    			System.out.println("You scored " + score + " - good job.");
    		} else if (score > 1) {
    			System.out.println("You scored " + score + " - you need to try harder.");
    		} else {
    			System.out.println("You scored " + score + " - it'd be worth getting extra help.");
    		}
    	}
    }

    And the output when I tested it:

    1.   11 - 4 = 7
    Correct!
     
    2.   15 + 5 = 20
    Correct!
     
    3.   16 - 3 = 13
    Correct!
     
    4.   11 - 5 = 6
    Correct!
     
    5.   12 - 9 = 9
    Incorrect - right answer is 3.
     
    6.   13 - 8 = 0
    Incorrect - right answer is 5.
     
    7.   15 + 6 = 21
    Correct!
     
    8.   14 - 6 = 8
    Correct!
     
    9.   16 - 4 = 12
    Correct!
     
    10.   17 - 4 = 14
    Incorrect - right answer is 13.
     
    You scored 7 - good job.
    Thank you for playing; hope to see you again soon!

    Thanks for pointing me in the right direction - much appreciated.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,265
    Thanks
    56
    Thanked 2,372 Times in 2,343 Posts

    Default Re: Random maths operator generation

    rightAnswer could be computed in the switch statement when the operator is set.

    Why use a switch and an if/else if. Use one OR the other, not both.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. How exactly does random block generation work in 2D/3D worlds?
    By vividMario52 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: February 24th, 2013, 04:27 PM
  2. Question. Lots of Maths!
    By djl1990 in forum What's Wrong With My Code?
    Replies: 9
    Last Post: October 28th, 2011, 11:57 AM
  3. Replies: 1
    Last Post: June 17th, 2011, 07:01 PM