Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
// Declare some variables you need
// -->
Scanner scan = new Scanner(System.in);
int endOption = 4;
int chosenOption = 0;
int countTo = 0;
int factorialCount2 = 0;
int lefty = 0;
do {
// Display the menu
displayMenu();
// Ask the user for one option
// -->
chosenOption = scan.nextInt();
switch (chosenOption) {
// Define four cases for different options. Don't forget "break".
// -->
case 1:
System.out.println("Enter a number: ");
countTo = scan.nextInt();
calcSum(countTo);
break;
case 2: System.out.println("Enter a number: ");
factorialCount2 = scan.nextInt();
factCont(factorialCount2);
break;
case 3: System.out.println("Enter a number: ");
lefty = scan.nextInt();
leftmostDig(lefty);
break;
case 4: System.out.println("Bye");
break;
}
} while (chosenOption<endOption);
scan.close();
}
/**
* Print the menu
*/
private static void displayMenu() {
System.out.println("Please choose one option from the following menu:");
System.out.println("1) Calculate the sum of integers from 1 to m");
System.out.println("2) Calculate the factorial of a given number");
System.out.println("3) Display the leftmost digit of a given number");
System.out.println("4) Quit");
}
private static int calcSum(int addingTo){
int sum = 0;
for(int i=1;i<=addingTo;i++){
sum = sum + i;
}
System.out.println("The sum of 1 to " + addingTo + " is " + sum);
System.out.println();
return sum;
}
private static int factCont(int number){
int multiply = 1;
for(int i=1; i<=number; i++){
multiply = multiply * i;
}
System.out.println("The factorial of " + number + " is " + multiply);
System.out.println();
return multiply;
}
private static int leftmostDig(int num){
int finalized = 0;
while(num >=10){
finalized = num/10;
}
System.out.println("The leftmost digit of " + num + " is " + finalized);
System.out.println();
return num;
}
}
So, yes this is a lab I am doing for school.. the only one that will not execute is case 3. I am not sure what exactly is happening. I tried this while I was at work on an online compiler and it worked. Now when I transfer it to the actual program I run into a snag. Let me know what you think it might be as I am very perplexed by what could be.
Your leftmostDig function contains a bug. If num is greater or equal to 10, it will never exit (it never changes the value of num). If you change it like the below, it will exit (and return the expected result).
private static int leftmostDig(int num) {
int finalized = num;
while (finalized >= 10) {
finalized = finalized / 10;
}
Related
/*Class MentalMathProgram
Michael
11/18/2020
This program is designed to present the user with randomly generated numbers
and it gets progressively harder for every question correct.
/
import java.util.;
public class mentalMathProgram {
static double ranNum(int min, int max){
Random ran = new Random();
double ranNum = min + (int)(Math.random() * ((max- - min)+ 1));
return (double)ranNum;
}
static byte mathType(int min, int max){
Random ran = new Random();
int mathType = min + (int)(Math.random() * ((max- - min)+ 1));
return (byte) mathType;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int restart = 0;
int correctAnswers = 0,incorrectAnswers = 0;
int numberOfQuestions = 0;
byte mathType = 0;
char again;
again = 'Y';
while(again == 'Y') {
do{
int questionCounter = 0;
System.out.println(" \n\nWelcome to your mental math assistance program! There will"
+ "\n be varying levels of difficulty as you progress through the questions"
+ "\n or when you select the difficulty preset. "
+ "\n\n Please select a difficulty below!");
System.out.println("\n 1. Easy"
+ "\n 2. Normal"
+ "\n 3. Medium"
+ "\n 4. Hard");
byte difficultyChoice = input.nextByte();
switch(difficultyChoice){
case 1: {
System.out.println("How many Questions do you want to do?");
numberOfQuestions = input.nextInt();
do {
byte randomOperationMin = 1;
byte randomOperationMax = 4;
byte operationValue = mathType(randomOperationMin,randomOperationMax);
mathType = operationValue;
switch(mathType) {
case 1: {
System.out.println("\n\n\n Easy difficulty Selected");
int easyMin = 1;
int easyMax = 10;
int result1=(int) ranNum(easyMin,easyMax);
int result2=(int) ranNum(easyMin,easyMax);
System.out.println("What is "+result1+ "+" +result2+ "=");
int userAnswer = input.nextInt();
int answer = result1 + result2;
if(userAnswer==answer) {
System.out.println("Correct!");
correctAnswers++;
}
else {
System.out.println("Incorrect! The Answer was "+answer);
incorrectAnswers++;
}
questionCounter = correctAnswers + incorrectAnswers;
break;
}
case 2: {
System.out.println("\n\n\n Easy difficulty Selected");
int easyMin = 1;
int easyMax = 10;
int result1=(int) ranNum(easyMin,easyMax);
int result2=(int) ranNum(easyMin,easyMax);
System.out.println("What is "+result1+ "-" +result2+ "=");
int userAnswer = input.nextInt();
int answer = result1 - result2;
if(userAnswer==answer) {
System.out.println("Correct!");
correctAnswers++;
}
else {
System.out.println("Incorrect! The Answer was "+answer);
incorrectAnswers++;
}
questionCounter = correctAnswers + incorrectAnswers;
break;
}
case 3: {
System.out.println("\n\n\n Easy difficulty Selected");
int easyMin = 1;
int easyMax = 10;
int result1=(int) ranNum(easyMin,easyMax);
int result2=(int) ranNum(easyMin,easyMax);
System.out.println("What is "+result1+ "*" +result2+ "=");
int userAnswer = input.nextInt();
int answer = result1 * result2;
if(userAnswer==answer) {
System.out.println("Correct!");
correctAnswers++;
}
else {
System.out.println("Incorrect! The Answer was "+answer);
incorrectAnswers++;
}
questionCounter = correctAnswers + incorrectAnswers;
break;
}
case 4: {
System.out.println("\n\n\n Easy difficulty Selected");
int easyMin = 1;
int easyMax = 10;
double result1=ranNum(easyMin,easyMax);
double result2=ranNum(easyMin,easyMax);
System.out.println("What is "+result1+ "/" +result2+ "=");
double userAnswer = input.nextDouble();
double answer = result1 / result2;
double remainder = result1 % result2;
System.out.println("The Remainder is "+remainder);
if(userAnswer==answer) {
System.out.println("Correct!");
correctAnswers++;
}
else {
System.out.println("Incorrect! The Answer was "+answer);
incorrectAnswers++;
}
questionCounter = correctAnswers + incorrectAnswers;
break;
}
}
}while(questionCounter != numberOfQuestions);
break;
//I need to figure out a way to loop this code over and over instead of it just breaking out. I also need to
// make it so that the user can exit the program whenever they want
}
}
}while(restart==0);//condition for the do while death/restart loop
System.out.println("\nPlay Again? Y OR N: ");
//println statement, asking if user would like to play again.
System.out.println("Questions Correct: "+correctAnswers+"");
again = input.nextLine().charAt(0);
// set variable again to value assigned from user input
}
}
}
This is my code but I'm very new to coding. Im just trying to reset the variable that controls the amount of questions presented to the user to reset at the end of each loop. So far I'm unable to figure out what I'm doing wrong
There are a number of issues with your code that makes it difficult to trace / debug.
If I understand correctly, your outer doWhile is supposed to run indefinitely until user chooses to terminate the program.
The second doWhile is controlling the number of questions that are being asked in any single, complete round of the game.
Firstly, bring the 'numberOfQuestions' variable to be within the scope of the outer loop.
Secondly, you can simply declare a boolean variable to control whether the user wants to continue playing the game or to terminate the program.
Lastly, for each of the switch cases, you can simply do questionCounter++, instead of summing the correct and incorrect answers.
boolean keepGoing = true;
do {
int numberOfQuestions = 0;
int questionCounter = 0;
System.out.println("How many questions?");
numberOfQuestions = sc.nextInt();
do {
// ask questions repeatedly
// for each case, questionCounter++
} while (questionCounter != numberOfQuestions);
System.out.println("Enter '0' to continue");
if (input.nextInt() != 0) {
keepGoing = false;
}
} while (keepGoing);
It is also good practice to make sure your lines are indented properly, so that you are able to see what codes belong in which block for better maintainability and debugging.
I put the code in a do-while loop. It asks the user which menu option they want and it computes the equation for them. The code is supposed to keep on going until the user hits 4 which is the quit option, but it stops after one sequence. I dont know what I need to change or add so it keeps on going.
import java.util.Scanner;
import java.text.DecimalFormat;
class Lab5
{
public static void main(String[] args) //header of the main method
{
Scanner in = new Scanner(System.in);
int choice;
int rem = 0;
int num;
do
{
//user prompt
System.out.print("Choose from the following menu\n1) Calculate the sum of integers 1 to m\n2) Factorial of a number\n3) Repeat the first number\n4) Quit\n:");
choice = in.nextInt();
switch(choice)
{
case 1:
int m, sum =0;
int i = 1;
System.out.print("Enter the number:");
m = in.nextInt();
while (i <= m)
{
sum=sum+i;
i++;
}
System.out.print("The sum of:" + m + ' ' + "is" + ' ' + sum);
break;
case 2:
int number, fact =1;
System.out.print("Enter the number:");
number = in.nextInt();
i=1;
for (int factor = 2; factor <= number; factor++)
{
fact = fact*factor;
}
System.out.print("The Factorial of +:" + number + ' ' + "is" + ' ' + fact);
break;
case 3:
System.out.print("Enter the number:");
num = in.nextInt();
while(num!=0)
{
rem = num%10;
num = num/10;
}
System.out.print("The leftmost digit is:" + rem);
break;
default:
break;
}
} while (choice == '4');
System.out.print(" ");
}
}
You wrote this as do ... while ( choice == '4' ), which means it will only continue if the user enters a 4.
Sounds like you want choice != '4'.
I'm creating a program to help with students solving y= m(x) + b. As of right now, I have the program to display the menu and evaluate if your response is correct to the answer. However, I need it to also count the number of correct answers in a row.
If 3 correct end program and output total correct out of attempts tried.
else if there were 3 attempts made the output a tip.
The main issue I'm having is the loop of the two (methods?). I apologize in advance if my code is atrocious, I'm having a hard time understanding methods and classes in this compared to how Python is. Anyone's suggestions or tips would be immensely helpful.
So far I've tried adding methods, and attempts at classes to certain parts of the program such as
public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable) {}
and
public static test_input() {}
However, now I'm facing scoping problems as well as errors referencing certain variables.
package algebra_Tutor;
import java.util.Scanner;
class AlgebraTutor {
public static void main(String[] args){
System.out.println("Enter 1 if you would like to solve for Y?");
System.out.println("Enter 2 if you would like to solve for M?");
System.out.println("Enter 3 if you would like to solve for B?");
System.out.println("Enter 4 to Quit");
//Asks for user input
System.out.print("Enter your selection: ");
}
//Creates random # for values in formula
int y_ = point_of_line_cross;
int m_ = slope;
int b_ = y_intercept;
int x_ = independent_variable;
public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable) {
// Creates scanner for input of menu Def as menu selector
Scanner user_Selection = new Scanner(System.in);
//Converts user input to an integer
int selection = user_Selection.nextInt();
user_Selection.close();
y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
slope = (int) Math.floor(Math.random() * 201) - 100;
point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
independent_variable = (int) Math.floor(Math.random() * 201) - 100;
//Tests what user input was, with expected output
if (selection == (1)) {
System.out.println("You chose to solve for Y: ");
System.out.println("Y = " +slope +"("+independent_variable+")"+" + "+y_intercept);
System.out.println("Input your answer: ");
}
else if (selection == (2)) {
System.out.println("You chose to solve for M: ");
System.out.println("M = "+"("+point_of_line_cross+" - "+y_intercept+")"+" / "+independent_variable);
System.out.println("Input your answer: ");
}
else if (selection == (3)) {
System.out.println("You chose to solve for B: ");
System.out.println("B = "+point_of_line_cross+" - "+slope+"("+independent_variable+")");
System.out.println("Input your answer: ");
}
else if (selection == (4)) {
System.out.println("You chose to quit the program. ");
return;
}
}
//Solves the problem in order to compare to User input
int answer_y = ((m_) * (x_)) + (b_);
int answer_m =(y_) - ((b_) / (x_));
int answer_b =(y_) - ((m_)* (x_));
public static test_input() {
//Problem solver defined
Scanner answer_input = new Scanner(System.in);
int answer = answer_input.nextInt();
//Creates loop for program
var counter = 0;
int correct = 0;
var answers_correct = false;
while (!answers_correct && correct < 3) {
if (answer == answer_y){
counter++;
correct++;
System.out.println("You answered correctly");
return;
}
else if (counter >= 3 && correct < 3) {
System.out.println("Youve been missing the questions lately, let me help! ");
}
else
{
System.out.println("Try again");
counter++;
correct = 0;
break;
}
}
}
}
I expect the program to output correct answers out of attempts after the user completes 3 problems in a row. In addition, it needs to output a tip after 3 attempts. And then after 3 correct, it should loop back to the beginning of program.
well I figured I would let you figure out how to make it loop on your own but I solved your other problems and put comments where I changed things. Hope this helps
//declared variables here. global variables must be declared static when accessed in a static method (ex: user_input())
static int y_;
static int m_;
static int b_;
static int x_;
public static void main(String[] args) {
// Creates scanner for input of menu Def as menu selector
Scanner user_Selection = new Scanner(System.in);
System.out.println("Enter 1 if you would like to solve for Y?");
System.out.println("Enter 2 if you would like to solve for M?");
System.out.println("Enter 3 if you would like to solve for B?");
System.out.println("Enter 4 to Quit");
//Converts user input to an integer
int selection = user_Selection.nextInt();
//call user_input()
user_input(selection);
}
public static void user_input(int selection) {
Scanner user_Selection = new Scanner(System.in);
int userAnswer;
int y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
int slope = (int) Math.floor(Math.random() * 201) - 100;
int point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
int independent_variable = (int) Math.floor(Math.random() * 201) - 100;
y_ = point_of_line_cross;
m_ = slope;
b_ = y_intercept;
x_ = independent_variable;
//Tests what user input was, with expected output
if (selection == (1)) {
System.out.println("You chose to solve for Y: ");
System.out.println("Y = " + slope + "(" + independent_variable + ")" + " + " + y_intercept);
System.out.println("Input your answer: ");
userAnswer = user_Selection.nextInt();
/*After user enters answer we test the answer by calling test_input
* */
test_input(userAnswer);
} else if (selection == (2)) {
System.out.println("You chose to solve for M: ");
System.out.println("M = " + "(" + point_of_line_cross + " - " + y_intercept + ")" + " / " + independent_variable);
System.out.println("Input your answer: ");
userAnswer = user_Selection.nextInt();
/*After user enters answer we test the answer by calling test_input
* */
test_input(userAnswer);
} else if (selection == (3)) {
System.out.println("You chose to solve for B: ");
System.out.println("B = " + point_of_line_cross + " - " + slope + "(" + independent_variable + ")");
System.out.println("Input your answer: ");
userAnswer = user_Selection.nextInt();
/*After user enters answer we test the answer by calling test_input
* */
test_input(userAnswer);
} else if (selection == (4)) {
System.out.println("You chose to quit the program. ");
}
}
// you forgot to include return type ex: void, int, String, double, float, etc
public static void test_input(int entered_answer) {
//Solves the problem in order to compare to User input
int answer_y = ((m_) * (x_)) + (b_);
int answer_m = (y_) - ((b_) / (x_));
int answer_b = (y_) - ((m_) * (x_));
//Problem solver defined
int answer = entered_answer;
//Creates loop for program
int counter = 0;
int correct = 0;
boolean answers_correct = false;
while (!answers_correct && correct < 3) {
if (answer == answer_y) {
counter++;
correct++;
System.out.println("You answered correctly");
return;
} else if (counter >= 3 && correct < 3) {
System.out.println("You've been missing the questions lately, let me help! ");
} else {
System.out.println("Try again");
counter++;
correct = 0;
break;
}
}
}
`
public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable)
If you give a method parameters, then when the method is called you will have to enter the values into the parameter yourself. I don't think this is what you intended because you defined what you wanted those parameter values to be here:
y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
slope = (int) Math.floor(Math.random() * 201) - 100;
point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
independent_variable = (int) Math.floor(Math.random() * 201) - 100;
In your test_input() method you wrote:
Scanner answer_input = new Scanner(System.in);
int answer = answer_input.nextInt();
.nextInt() will make the program halt and wait for user input so you don't want to use it until you are ready to get the input.
I don't really know much about the var keyword in java but rather than using var I figured you should just declare the variable type so from this:
var counter = 0;
to this:
int counter = 0;
and to get a better understanding on how methods work I recommend these two videos:
Intro to java methods
Java method parameters and return types
For an in depth explanation of the fundamentals of java in general then I recommend this whole playlist
Java Beginner Programming
It's quite late on a saturday for me to do algebra, so I will stick to suggesting changes to the structure of your program. First, you can accomplish everything with a single class to contain the questions, and score for the user. The methods in that class can be chosen via a menu in the main.
I wrote a sample of how I would structure this based on standard Java OOP methodology. In my program, the main needs no static class, it loops a menu, and the choice of a question is made there. My methods hava single question, you can add as many as you like in the menu, the important thing is the structure.
import java.util.Scanner;
//This class contains the two methods and over-all score
class Material {
private int score;
//The user chooses this or the earth method
public void sky() {
String answer = "null";
int count = 0;
Scanner input = new Scanner(System.in);
//within the method, is this while loop which gives a hint after 3 attempts.
while (!answer.equals("blue") && (!answer.equals("exit"))) {
System.out.println("What color is the sky? 'exit' to exit");
answer = input.nextLine();
count++;
if (count == 3)
System.out.println("Hint: It starts with a 'b'");
}
if (answer.equals("blue"))
score += 1;//The score will increment if the choice is correct,
else//or else leave with nothing...
return;
}
//This method is the same as the sky() method, just different question and answer.
public void earth() {
String answer = "null";
int count = 0;
Scanner input = new Scanner(System.in);
while (!answer.equals("iron") && (!answer.equals("exit"))) {
System.out.println("What is the core made of? 'exit' to exit");
answer = input.nextLine();
count++;
if (count == 3)
System.out.println("Hint: It starts with a 'i'");
}
if (answer.equals("iron"))
score += 1;
else
return;
}
public int getScore() {
return score;
}
}
public class Questions {
public static void main(String[] args) {
//No static methods needed, here is an instance of our test materia class.
Material material = new Material();
//The choice and scanner are instantiated here.
int choice = 0;
Scanner input = new Scanner(System.in);
//This while loop uses a switch statement to choose the methods for the questions
while (choice != 3) {
if (material.getScore() == 3) {
System.out.println("Good job, you scored three right.");
return;
}
System.out.println("SCORE: " + material.getScore());
System.out.println("Anwer questions about the sky: 1");
System.out.println("Answer quetions about the earth: 2");
System.out.println("Exit: 3");
choice = input.nextInt();
//choices are 1 , 2 for questions, and 3 to leave.
switch (choice) {
case 1:
material.sky();
break;
case 2:
material.earth();
break;
case 3:
System.out.println("Exiting...");
break;
default:
System.out.println("not a valid number choice...");
}
}
}// main
}// class
Side note: instead of asking the user for 1, 2, 3 or 4, you should directly ask them to enter the variable they want to solve:
Solve the equation y = m * x + b for which variable (y, m, b, quit)?
This makes the users of the program think more in the problem domain instead of some technically useless indirection.
As you have a Python background you should know that the indentation of the lines is important and has meaning. It's the same for Java programs. The only difference is that the Java compiler ignores the indentation completely. But Java programs are also read by humans, and for them the indentation is viable for understanding the structure of the program. The code you posted has inconsistent indentation, and you should let your IDE fix that.
Your program should be structured like this:
public class AlgebraTutor {
private final Scanner in = new Scanner(System.in);
private final PrintStream out = System.out;
private int attempts = 0;
void solveForY() {
...
}
void solveForM() {
...
}
void solveForB() {
...
}
void mainMenu() {
while (true) {
out.println("Solve the equation y = m * x + b for which variable (y, m, b), or quit?");
if (!in.hasNextLine()) {
return;
}
switch (in.nextLine()) {
case "y":
solveForY();
break;
case "m":
solveForX();
break;
case "b":
solveForB();
break;
case "q":
case "quit":
return;
}
}
}
public static void main(String[] args) {
new AlgebraTutor().mainLoop();
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
write a program that repeatedly prompts a user to supply score(out of 100) on a test for 5 students once the program has real all score it should produce a table with the following headings (and automatically fill in the rest of the table) for example
Student No # Score(out of 100)
1 55
2 66
The program should them calculate the total score
Here is my code
import java.io.*;
import java.util.*;
public class test33 {
public static void main(String[]args){
Scanner kbReader = new Scanner (System.in);
int scores[] = new int [100];
int counter = 0;
int sum = 0;
int input = 0;
do {
System.out.println("Enter score out of 100 or negative to break.");
input = kbReader.nextInt();
if (input < 0) {
break;
} else if (input > 100) {
System.out.println("Score must be out of 100");
} else {
scores[input]++;
counter++;
sum += input;
}
} while (input > 0);
System.out.println("Score\t# of occur...");
for (int i = 0; i < 100; i++) {
System.out.println(i + "\t" + scores[i]);
}
System.out.println("The mean score is " +(sum/counter));
}
}
scores[input]++; if you want to assign value to your array scores[] you must corrected like i did below.
public static void main(String[]args) {
Scanner kbReader= new Scanner (System.in);
int scores[] = new int [100];
int counter = 0;
int sum = 0;
int input = 0;
do {
System.out.println("Enter score out of 100 or negative to quit.");
input=kbReader.nextInt();
if(input<0) {
break;
}
else if (input>100) {
System.out.println("Score must be out of 100");
} else {
scores[counter]=input;
counter++;
sum+=input;
}
} while (input>0);
if(counter != 0){
System.out.println("Score\t# of occur...");
for(int i =0; i<100; i++) {
System.out.println(i + "\t" + scores[i]);
};
System.out.println("The mean score is " +(sum/counter));
}
}
So my objective is to create a maths game where the user selects if he/she wants a maths question from a file or a random generate one consisting of the 4 maths elements in 3 difficulties.I have created a lot of methods... I have an idea where im going but now im stuck. I need to have it so it keeps a score of questions answered correctly. How do i return the points to the main method and have the game going until the user presses 3 on the gamePlay()method
public class MathsGameProject2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int score;
int points = 0;
int questionType;
System.out.print("Please enter the what type of question you want" + "\n 1 Question from a file" + "\n 2 Random question" + "\n 3 Quit game\n");
questionType = keyboard.nextInt();
while (questionType != 3) {
if (questionType == 1) {
questionFromFile();
} else if (questionType == 2) {
randomQuestion();
} else {
System.out.println("Please enter the what type of question you want" + "\n 1 Question from a file" + "\n 2 Random question" + "\n 3 Quit game\n");
}
}
}
public static questionFromFile() {
}
public static randomQuestion() {
Scanner keyboard = new Scanner(System.in);
int difficulty;
System.out.println("Please enter the difficulty you want to play." + "\n 1. Easy" + "\n 2. Medium" + "\n 3. Hard\n");
difficulty = keyboard.nextInt();
if (difficulty == 1) {
easy();
} else if (difficulty == 2) {
medium();
} else if (difficulty == 3) {
hard();
} else {
System.out.println("Please enter a number between 1-3\n");
}
}
public static easy() {
Scanner keyboard = new Scanner(System.in);
int mathElement;
System.out.print("What element of maths do you want?" + "\n1 Additon" + "\n2 Subtraction" + "\n3 Multiplication" + "\n4 Division\n");
mathElement = keyboard.nextInt();
if (mathElement == 1) {
easyAdd();
} else if (mathElement == 2) {
easySub();
} else if (mathElement == 3) {
easyMulti();
} else if (mathElement == 4) {
easyDiv();
} else {
System.out.println("Please enter a number between 1-4\n");
}
}
public static easyAdd() {
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
int num = rand.nextInt(10) + 1;
int num2 = rand.nextInt(10) + 1;
int correct = num + num2;
int answer;
System.out.print("What is the answer of " + num + " + " + num2 + " ?");
answer = keyboard.nextInt();
if (answer == correct) {
}
}
In order to keep track of how many questions the user answers successfully, you will need to:
For each question, return whether or not the user answered correctly
Have a counter which increments whenever a user answers a question correctly
Optionally, have a counter which increments whenever a question is answered wrong
For #1, you can use a boolean return value for specifying if the question was answered successfully.
return (answer == correct);
You will want to propagate that return value all the way up to the main() method.
static void main() {
....
boolean isCorrect = randomQuestion();
....
}
static boolean randomQuestion() {
....
return easy();
....
}
static boolean easy() {
....
return easyAdd();
....
}
static boolean easyAdd() {
...
return (answer == correct);
}
Then for #2 and #3, you can increment counter(s) defined in main based on the value returned by randomQuestion()
int numberCorrect = 0;
int numberWrong = 0;
....
boolean isCorrect = randomQuestion();
if (isCorrect) {
numberCorrect++;
} else {
numberIncorrect++;
}
Additionally (no pun intended), you can use a while loop to continuously receive user input until you get your exit code, which in this case is 3. One way to do this is to use a while(true) loop and break out when the user enters 3.
while (true) {
/* Get user input */
....
if (questionType == 3) {
break;
}
}
Finally, after your loop, you can simply print out the value of your numberCorrect and numberIncorrect counters.
Hope this helps.