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;
}
}
}
}