• 0

Need some help with a Java programming assignment.


Question

I wrote a program called SubtractionQuizLoop.java that prompts the user to answer some easy subtraction questions. Now, I want to modify it to ask for addition, subtraction, multiplication and division. To do that, I have to make use of the switch, which I'm just learning about and thus am a little unsure on its usage.

Here's my SubtractionQuizLoop.java source code...

import java.util.Scanner;

public class SubtractionQuizLoop {
	public static void main(String[] args) {
		final int NUMBER_OF_QUESTIONS = 5; // Number of questions
		int correctCount = 0; // Count the number of correct answers
		int count = 0; // Count the number of questions
		long startTime = System.currentTimeMillis();
		String output = ""; // output string is initially empty
		Scanner input = new Scanner(System.in);

		while (count < NUMBER_OF_QUESTIONS) {
			// 1. Generate two random single-digit integers
			int number1 = (int)(Math.random() * 10);
			int number2 = (int)(Math.random() * 10);

			// 2. If number1 < number2, swap number1 with number2
			if (number1 < number2) {
				int temp = number1;
				number1 = number2;
				number2 = temp;	
			}

			// 3. Prompt the student to answer "What is number1 - number2?"
			System.out.print(
				"What is " + number1 + " - " + number2 + "? ");
			int answer = input.nextInt();

			// 4. Grade the answer and display the result
			if (number1 - number2 == answer) {
			System.out.println("You are correct!");
			correctCount++;
			}	
			else
			System.out.println("Your answer is wrong. \n" + number1
				+ " - " + number2 + " should be " + (number1 - number2));

			// Increase the count
			count++;

			output += "\n" + number1 + "-" + number2 + "=" + answer +
				((number1 - number2 == answer) ? " correct" : " wrong");
		}

		long endTime = System.currentTimeMillis();
		long testTime = endTime - startTime;

		System.out.println("Correct count is " + correctCount +
			"\nTest time is " + testTime / 1000 + " seconds\n" + output);
	}
}

Here are my project's specifications...

~ Lets user decide how many questions will be asked.

~ Lets user decide if the questions will be (1) all addition or (2) all subtraction or

(3) all multiplication or ( 4) all division or (5) a random mix of these operations.

A random mix means any question is equally likely to be +, _ , * or /.

~ Lets user decide on the level of the problems. Level (1) is single digit

numbers randomly chosen for 0 to 9 and Level(2) is single or double digit

numbers randomly chosen from 0 to 99.

The switch command is supposed to be expressed in this form:

switch ( choice) { case 1: //addition question code
}
break; case 2: //subtraction question code from Listing 4.3
break; case 3: // multiplication question code
break: case 4: //division question code
break: default: // print error message
System.exit(0);

I know that's a lot for one topic. But I'm just feeling a bit overwhelmed here and was wondering if maybe someone here could help me get started.

Link to comment
Share on other sites

7 answers to this question

Recommended Posts

  • 0

You already should know how to do the first task. Instead of using the constant: NUMBER_OF_QUESTIONS, create a int variable and have the user input the number.

As for the second task, You already have the basic outline for the switch statement. I would just add an if statement before the switch statement that checks the choice number to 5 (The random indentifier). If they are the same then have the choice number changed to a random number (1-4). That way it will perform one of the question operations in the switch statement.

The third task is something you also already know. At the beginning of the program after getting the input for the number of questions, prompt the user for the difficulty. Once that is obtained change the number1 & number2 random initialization to an if statement that checks the difficulty variable. If the difficulty equals 1 use the code already there, else use the same set operations, modified to be random between 0 and 99.

I do not want to just give you the code since the discovery of implementation is part of the learning process. Anyway, I hope this helps.

Link to comment
Share on other sites

  • 0

Your example switch block has a few problems, too.

switch ( choice) { case 1: //addition question code

}

break; case 2: //subtraction question code from Listing 4.3

break; case 3: // multiplication question code

break: case 4: //division question code

break: default: // print error message

System.exit(0);

The bracket needs to go at the end, and unless I'm mis-remembering, the default case needs to have a break (or some other terminator) too.

switch ( choice) {
	case 1: //addition question code
		break;

	case 2: //subtraction question code from Listing 4.3
		break;

	case 3: // multiplication question code
		break:

	case 4: //division question code
		break:

	default: // print error message
		System.exit(0);
}

or

switch ( choice) {
	case 1: //addition question code
		break;

	case 2: //subtraction question code from Listing 4.3
		break;

	case 3: // multiplication question code
		break:

	case 4: //division question code
		break;

	default: // print error message
		break;
}

System.exit(0);

Keeping the break keywords with the corresponding case statement helps with readability, too. :)

Link to comment
Share on other sites

  • 0

Okay, someone who is good with Java gave me quite a bit of help, and we came up with this:

import java.util.Scanner;

public class MathQuiz {
	public static void main(String[] args) {	
	Scanner input = new Scanner(System.in);
		int numQuestions = 0;
		int choice = 0;
		int level = 0;
		int numCorrect = 0;
		getNumQuestions();
		getQuestionType();
		getQuestionLevel();
		long startTime = System.currentTimeMillis();
		askQuestions();
		long endTime = System.currentTimeMillis();
		printReport(startTime-endTime);
	}

	public getNumQuestions() {
		while (numQuestions < 1)
		{
			System.out.print("How many questions? ");
			numQuestions = input.nextInt();
			if (numQuestions < 1)
			{
				System.out.println("Invalid - must ask at least 1 question");
			}
		}
	}	

	public void getQuestionType() {
		while (choice < 1 || choice > 5)
		{
			System.out.println("Please select the type of questions you would like");
			System.out.println("1) Addition");
			System.out.println("2) Subtraction");
			System.out.println("3) Multiplication");
			System.out.println("4) Division");
			System.out.println("5) Mixed");
			System.out.print("Type: ");
			choice = input.nextInt();
			if (choice < 1 || choice > 5)
			{
				System.out.println("Choice must be in the range 1-5"); 
			}
		}
	}

	public void getQuestionLevel() {
		while (level < 1 || level > 2)
		{
			System.out.println("Please select the level of questions you would like");
			System.out.println("1) Single Digit");
			System.out.println("2) Double Digit");
			System.out.print("Level: ");
			level = input.nextInt();
			if (level < 1 || level > 2)
			{
				System.out.println("Level must be 1 or 2");
			}
		}
	}

	public void askQuestions() {
		for (int i = 0; i < numQuestions; i++)
		{
			int num1 = genRandomNum(level);
			int num2 = genRandomNum(level);
			int sign = choice;
			if (sign == 5)
			{
				sign = (int)(Math.random() * 4 + 1);
			}
			switch(sign)
			{
				case 1: addition(num1, num2);
					break;
				case 2: subtraction(num1, num2);
					break;
				case 3: multiplication(num1, num2);
					break;
				case 4: division(num1, num2);
					break;
				default: System.out.println("Error");
					System.exit(1);
			}
		}
	}

	public int genRandomNum(int difficulty) {
		if (difficulty == 1)
		{
			return (int)(Math.random() * 10);
		}
		else
		{
			return (int)(Math.random() * 100);
		}
	}

	public void addition(int num1, int num2) {
		System.out.print("What is " + num1 + " + " + num2 + "? ");
		int answer = input.nextInt();
		if (num1 + num2 == answer)
		{
			System.out.println("Correct");
			numCorrect++;
		}
		else 
		{
			System.out.println("Incorrect -> " + num1 + " + " + num2 + " = " + num1+num2);
		}
	}

	public void subtraction(int num1, int num2) {
		System.out.print("What is " + num1 + " - " + num2 + "? ");
		int answer = input.nextInt();
		if (num1 - num2 == answer)
		{
			System.out.println("Correct");
			numCorrect++;
		}
		else 
		{
			System.out.println("Incorrect -> " + num1 + " - " + num2 + " = " + num1+num2);
		}
	}

	public void multiplication(int num1, int num2) {
		System.out.print("What is " + num1 + " * " + num2 + "? ");
		int answer = input.nextInt();
		if (num1 * num2 == answer)
		{
			System.out.println("Correct");
			numCorrect++;
		}
		else 
		{
			System.out.println("Incorrect -> " + num1 + " * " + num2 + " = " + num1+num2);
		}
	}

	public void division(int num1, int num2) {
		boolean quotientCorrect = false;
		boolean remainderCorrect = false;
		System.out.print("What is the quotient of " + num1 + " / " + num2 + "? ");
		int answer = input.nextInt();
		System.out.print("What is the remainder of " + num1 + " / " + num2 + "? ");
		int remainder = input.nextInt();
		if (num1 / num2 == answer)
		{
			quotientCorrect = true;
		}
		if (num1 % num2 == remainder)
		{
			remainderCorrect = true;
		}
		if (quotientCorrect && remainderCorrect)
		{
			System.out.println("Correct");
			numCorrect++;
		}
		else
		{
			System.out.println("Incorrect -> " + num1 + " / " + num2 + " = " + num1/num2 + "r" + num1%num2);
		}
	}

	public void printReport(long totalTime) {
		System.out.println("Number of correct responses: " + numCorrect + "/" + numQuestions);
		double percent = numCorrect/numQuestions;
		System.out.println("Your percentage: " + percent + "%");
		System.out.println("Total time taken: " + totalTime/1000 + "s");
		System.out.println("Average time per question: " + (totalTime/numQuestions)/1000 + "s");
	}
}

The problem now is when I go to compile, I'm getting an error with line 25, which is:

	public getNumQuestions() {

Earlier, this said public static getNumQuestions(), which caused 39 compiling errors. When I removed static, I'm down to just one. But it's an error I've not seen before: invalid method declaration. Does anyone know how I can fix this compiling error?

Link to comment
Share on other sites

  • 0
	public getNumQuestions() {

Earlier, this said public static getNumQuestions(), which caused 39 compiling errors. When I removed static, I'm down to just one. But it's an error I've not seen before: invalid method declaration. Does anyone know how I can fix this compiling error?

All method declarations need a return type - use void if there is no return value.

Link to comment
Share on other sites

  • 0
[code]	public getNumQuestions()

Should be:

public void getNumQuestions()

There are a couple more errors with the code you posted which will prevent it from working, though. All your methods except for main are non-static, but you don't instantiate a MathQuiz anywhere from the Main() method, so you won't be able to call them. Just to remind you, static methods can be called directly from Main(), but non-static methods must be called on an instance of the class, for instance:

MathQuiz mathQuiz = new MathQuiz();

mathQuiz.getNumQuestion() etc.

You need to decided whether you are using only static methods or instantiate a MathQuiz and use instance methods.

Also you are declaring the Scanner inside the Main() method, but trying to use it in other methods. That will definitely not compile. You need to declare it at the class scope. Again, if you declare it static, then it can be used by static methods, but if you don't, it's per-instance only. If you need any more clarifications on this please don't hesitate to ask.

:)

Edited by Dr_Asik
Link to comment
Share on other sites

  • 0
........

The problem now is when I go to compile, I'm getting an error with line 25, which is:

	public getNumQuestions() {

Earlier, this said public static getNumQuestions(), which caused 39 compiling errors. When I removed static, I'm down to just one. But it's an error I've not seen before: invalid method declaration. Does anyone know how I can fix this compiling error?

Read up on the difference between static and non-static methods, and public/private and return types :) That will make it much easier in future to write your method declarations and with your planning of programs.

IIRC, if you use void, then you can't have a return statement in there (it will automatically return without it, but won't pass any value back to the original caller of that method). If you use, say, int, then you have to return something that is an int.

Link to comment
Share on other sites

  • 0

Okay, I finally got the program all sorted out. I ended up changing it quite a bit from the original, but it works perfectly now. Thanks to everyone who gave me some tips.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.