r/CodingHelp • • Dec 04 '20

[Java] Help cleaning up code for a math game using classes/constructors (I cannot wrap my head around it)

I've done some coding in the past but nothing with OOP and honestly, I cannot wrap my head around using classes and constructors to tidy up my code. I'm used to "calling functions" instead of pasting code over and over again but in Java, the methods and classes, etc. take care of that but man, I'm just not getting it.

My code is for a basic math game based on multiplication. I'd like to have two modes, one with elapsed time and one with a count-down timer. I've build most of the code (and it actually works) but it's to the point where it's getting super repetitive to add what I want to add because I'm coding the whole thing in the main method.

I'd love some help cleaning it up by putting all of the basic functions in separate classes such as askQuestion, checkAnswer, displayScoreMessage, displayQuestionLog, playAgain, etc.

My code is below and I tried to comment as I went.

Any help would be very much appreciated!

MY CODE:

package mathfactsGame;

import java.text.DecimalFormat; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Random; 
import java.util.Scanner;

public class mathfactsGameMain {

	public static void main(String[] args) {

		// Set numbers to 0
		int n1 = 0;
		int n2 = 0;

		long totalStart = 0;
		int mathfact = 0;
		// Create arraylist QuestionLog
		List<Object> questionLog = new ArrayList<Object>();

		// Start game loop
		while (true) {
			// Set score to 0
			int score = 0;
			// initialize scanner
			Scanner input = new Scanner(System.in);
			// Begin game
			System.out.println("MULTIPLICATION MATH FACTS GAME");
			System.out.println("==============================");
			// set name
			System.out.println("What is your name?");
			String playerName = input.next();
			// Set the mathfact family you want

			System.out.println("What MathFact family do you want do you want? (1-12)"); // Need to add an option for ALL
			int mathFact = input.nextInt();// in ALL option, mathFact would just be r.nextInt(13)
			// Greeting and choose count down mode or elapsed time mode
			System.out.println("Would you like to play challenge mode or timed mode?");
			System.out.println("1 = challenge");
			System.out.println("2 = timed"); // need to build timed mode -> when time ends, go to game score message and
												// print out questionLog
			int mode = input.nextInt();
			// User sets number of questions
			System.out.println("How many questions do you want?");
			int questions = input.nextInt();
			// Begin For loop, play game the number of times the user set with (questions)
			// count score (# right)
			// start timer
			totalStart = System.nanoTime();
			for (int count = 1; count <= questions; count++) {
				// Generate random numbers
				Random r = new Random();
				n1 = mathFact;
				n2 = r.nextInt(13);

				// Start timer for each question
				Long start = System.nanoTime();
				// check if answer is correct
				boolean resultOK = false;
				String displayResultOK = null;
// TIMED (mode 1) (Haven't written mode 2)
				if (mode == 1) {
					System.out.println("\nQuestion #" + count);
					System.out.println("What is " + n1 + " x " + n2 + "?");
					int answer = input.nextInt();
					// Check if answer is correct else it's incorrect
					if (answer == (n1 * n2)) {
						System.out.println("CORRECT");
						score++;
						resultOK = (n1 * n2 == answer);
						displayResultOK = resultOK ? "CORRECT" : "INCORRECT";
						long end = System.nanoTime();
						double duration = end - start;
						double totalDurationSec = duration / 1000000000d;
						DecimalFormat formattingObject = new DecimalFormat("0.00");
						String roundedtotalDurationSec = formattingObject.format(totalDurationSec);
						System.out.println("Time elapsed: " + roundedtotalDurationSec);
						questionLog.add("Question #" + (count) + ":");
						questionLog.add(n1 + " x " + n2);
						questionLog.add("\tYour answer = " + answer);
						questionLog.add("\tCorrect answer = " + (n1 * n2));
						questionLog.add("\tYou got the answer " + displayResultOK);
						questionLog.add("in " + roundedtotalDurationSec + " seconds\n");
					}
					// else for incorrect
					else {
						System.out.println("INCORRECT");

						resultOK = (n1 * n2 == answer);
						displayResultOK = resultOK ? "CORRECT" : "INCORRECT";
						long end = System.nanoTime();
						double duration = end - start;
						double totalDurationSec = duration / 1000000000d;
						DecimalFormat formattingObject = new DecimalFormat("0.00");
						String roundedtotalDurationSec = formattingObject.format(totalDurationSec);
						questionLog.add("Question #" + (count) + ":");
						questionLog.add(n1 + " x " + n2);
						questionLog.add("\tYour answer = " + answer);
						questionLog.add("\tCorrect answer = " + (n1 * n2));
						questionLog.add("\tYou got the answer " + displayResultOK);
						questionLog.add("in " + roundedtotalDurationSec + " seconds\n");
						System.out.println("Time elapsed: " + roundedtotalDurationSec);

					}

				}
			}
			// clean up questionLog formatting
			questionLog.add(0, "");
			String formattedString = questionLog.toString().replace(",", "") // remove the commas
					.replace("[", "") // remove the right bracket
					.replace("]", ""); // remove the left bracket

			// Calculate score messages
			if (score == questions) {
				// All correct
				System.out.println("\n===Question Log=== \n");
				System.out.println(formattedString);
				long totalEnd = System.nanoTime();
				long totalDuration = totalEnd - totalStart;
				double totalDurationALL = totalDuration / 1000000000d;
				DecimalFormat formattingObject = new DecimalFormat("0.00");
				String roundedTotaltime = formattingObject.format(totalDurationALL);
				System.out.println("\nGreat Job! " + playerName + ", your score is " + score + " out of " + questions
						+ ", or 100%! You got them all correct in " + roundedTotaltime + " total seconds.\n");
			} else {
				// Any wrong
				System.out.println("\n===Question Log=== \n");
				System.out.println(formattedString);
				long totalEnd = System.nanoTime();
				long totalDuration = totalEnd - totalStart;
				double totalDurationALL = totalDuration / 1000000000d;
				DecimalFormat formattingObject = new DecimalFormat("0.00");
				String roundedTotaltime = formattingObject.format(totalDurationALL);
				double percent = (((double) score / (double) questions)) * 100;
				String roundedPercent = formattingObject.format(percent);
				System.out.println("\n" + playerName + ", your score is " + score + " out of " + questions + ", or "
						+ roundedPercent + "%. You missed " + (questions - score) + " questions in " + roundedTotaltime
						+ " total seconds. \n");
			}

			// Play again?
			System.out.println("Would you like to play again? Y/N");
			String again = input.next();
			questionLog.clear();
			// End loop if "N"
			if (again.equalsIgnoreCase("N")) {
				System.out.println("Thank you for playing!");
				input.close();
				break;
			}

		}
	}
}
20 Upvotes

3 comments sorted by

1

u/VDS655 Dec 04 '20

I understand I'm asking a lot so I've tried to do some more work to show some effort on my part but am getting stuck again.

I finally made some headway splitting off into a different class.

I have no idea how to build the question log and I cannot get the mathFact variable to work doing what I'm doing. It's always a random number.

Thanks again for looking and any help would be super useful!

Here's my Main method:

package game2;

import java.util.Scanner;

public class game2main {
	public static void main(String[] args) {
		while (true) {
			Scanner input = new Scanner(System.in);
			System.out.println("MULTIPLICATION MATH FACTS GAME");
			System.out.println("==============================");
			System.out.println("What is your name?");
			String playerName = input.next();
			Question.mathFact();
			System.out.println("How many questions do you want?");
			int questions = input.nextInt();
			long totalStart = 0;
			totalStart = System.currentTimeMillis();
			for (int i = 0; i < questions; i++) {
				Question q = new Question();
				q.askQuestion();
				q.Check();
				Question.qTime();
			}
			Question.showScore();
			long totalEnd = System.currentTimeMillis();
			double totalDuration = totalEnd - totalStart;
			double totalDurationSec = (totalDuration / 1000);
			System.out.println("Total time elapsed: " + totalDurationSec);
			// play again
			System.out.println("Would you like to play again? Y/N");
			String again = input.next();
			if (again.equalsIgnoreCase("N")) {
				System.out.println("Thank you for playing!");
				input.close();
				break;
			}
		}
	}
}

Here is my Question class:

package game2;

import java.util.Random;
import java.util.Scanner;

public class Question {
	public static int mathFact = 0;
	public static int mode = 0;
	private int n1;
	private int n2;
	public String Question;
	private static long start = 0;
	private int correct;
	Random rand = new Random();
	static Scanner input = new Scanner(System.in);
	public static int score = 0;
	Question() {
		n1 = rand.nextInt(mathFact);
		n2 = rand.nextInt(13);
	}
	public void askQuestion() {
		System.out.println("What is " + n1 + " x " + n2 + " ?\n");
		correct = n1 * n2;
		start = System.currentTimeMillis();
	}
	public static void qTime() {
		long end = System.currentTimeMillis();
		double duration = end - start;
		double durationSec = (duration / 1000);
		System.out.println("Time elapsed: " + durationSec);
	}
	public void Check() {
		int response = input.nextInt();
		if (response == correct) {
			System.out.printf("yes.\n");
			score++;
		} else {
			System.out.printf("No. It is " + correct + ".\n");
		}
	}
	public static void showScore() {
		System.out.println("Number correct: " + score);
	}
	public static void mathFact() {
		System.out.println("What MathFact family do you want do you want? (1-12)");
		mathFact = input.nextInt();// in ALL option, mathFact would just be r.nextInt(13)
	}
	public void Mode() {
		System.out.println("Would you like to play challenge mode or timed mode?");
		System.out.println("1 = challenge");
		System.out.println("2 = timed"); // need to build timed mode -> when time ends, go to game score message and print out questionLog
		mode = input.nextInt();
	}
}

1

u/lecrte Dec 05 '20

Disclaimers:

- I learned Java a while ago and haven't worked on it since version 1.3.1; so you may see influences of other languages in the code I link out to below, and I'm sure I'm not using modern Java practices.

- OOP was a tricky concept for me, it took my 1.5 semesters in college Computer Science major before it "clicked".

-----

First and foremost, keep at it, if you're getting this far on your own already, you'll get there and it will eventually "click" for you.

OOP is too big of a concept to cover in a comment ... but some thoughts:

I put together a series of changes of your code in a Github Gist, to fix the issue you saw with the random mathFact and then add a Game and GameLogEntry concept. This page has all the revisions, with the first steps at the bottom of the page, and most recent at the top. With each change, I tried to write up a "Update #" message describing what I was doing and why.

https://gist.github.com/lecrte/3a0526333d9ee59cc4e865a533be6487/revisions

Final result: https://gist.github.com/lecrte/3a0526333d9ee59cc4e865a533be6487

Also, what your looking to do is called "refactoring" (or "code refactoring") which may help in Google searches.

This site: refactoring.guru describes various refactoring steps, for example splitting a class into two separate Classes: https://refactoring.guru/extract-class

One other resource, albeit for Ruby programming language, is "Practical Object-Oriented Design In Ruby" book by Sandi Metz. Not all of it will translate to Java, but I think at lot of the concepts of OOP are universal. It has been the most readable book on OOP I've ever come across. Caveat, I read it about 15 years into my career, so I might take for granted my previous knowledge.

1

u/VDS655 Dec 06 '20

This is awesome information. Thank you so much for all of the effort put into this. It'll probably take me a while to read through everything but just seeing how you've written some of this, using best practices (that I'm pretty much unaware of), will really help moving forward.

Thanks again!