I am tasked with creating a quizz program in Java which asks the user to find the answer to 10 addition / subtraction problems form ( a + b ) or ( a - b) = c, where "a" and "b" are random numbers.
I was able to do the first part where "a" and "b" get randomly generated and the user is told whether or not their answer is correct. I am stuck on how to generate this question 10 times and how to randomly chose whether the operator is "+" or "-". Below is the code I have so far:
import java.util.Scanner;
import java.util.Random;
public class LetsSee{
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
int sum = 0;
int userAnswer ;
int check ;
// Random number generating
Random generator = new Random();
int N1 = generator.nextInt(100);
int N2 = generator.nextInt(N1);
System.out.println(" What is the answer to " + N1 + " + " + N2 + " = " );
userAnswer = new Scanner(System.in).nextInt();
// Display if its correct or not
check = N1 + N2;
if(userAnswer == check){
System.out.println("You are correct!");
}
else{
System.out.println(" Sorry, the correct answer is : " + check);
}
}
}
Help would be GREATLY appreciated. Thanks !
So I came up with a quick solution that would look something like this
Random generator = new Random();
int var1 = generator.nextInt(100);
int var2 = generator.nextInt(100);
int choice = generator.nextInt(3);
switch (choice){
case 0:
System.out.println(var1 + " + " + var2);
break;
case 1:
System.out.println(var1 + " - " + var2);
break;
case 2:
System.out.println(var1 + " * " + var2);
break;
case 3:
System.out.println(var1 + " / " + var2);
break;
}
This is just a rough solution, nothing fancy, but hopefully gives you the idea of what you're looking for.
You needed a choice of one of 4 operators, so I've randomly picked a number from 0-3 to get a random operator, which we can then use in a switch to generate a question based on our 2 random numbers
Let me know if this helps. I just added a for loop to ask the user for input 10 times and then built the +/- based off whether a random int was even or odd.
import java.util.Scanner;
import java.util.Random;
public class HelloWorld{
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
int sum = 0;
int userAnswer ;
int check ;
// Random number generating
// Ask the user for input 10 times
for (int i = 0; i < 10; i++) {
Random generator = new Random();
int N1 = generator.nextInt(100);
int N2 = generator.nextInt(N1);
int N3 = generator.nextInt(2);
// if N3 is even use plus, if odd use minus
Boolean plus = N3 % 2 == 0;
// Set a string to either "+" or "-" depending on the value of plus
String plusMinus = plus? "+" : "-";
System.out.println(" What is the answer to " + N1 + plusMinus + N2 + " = " );
userAnswer = new Scanner(System.in).nextInt();
// Display if its correct or not
// Set the answer depending on the value of plus.
check = plus? N1 + N2 : N1 - N2;
if(userAnswer == check){
System.out.println("You are correct!");
}
else{
System.out.println(" Sorry, the correct answer is : " + check);
}
}
}
}
Related
I am trying to make a program that solves for all the 2 number combinations of addition and subtraction that equal a target value.
For example, given the array [12,1,9,11,32,19] and the target value twenty, the answers 1+19, 9+11, and 32-12 must be returned. If there are no possible combinations, the System should print that there are no possible combinations. Also, every combination must be two numbers ONLY. Is it possible to do this only in the main class?
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("What length (in a whole number) would you like the array to be? ");
int arraySize = sc.nextInt();
int [] arr = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
int remainingNumbers = arraySize - i;
System.out.println("Please enter " + remainingNumbers + " more integers.");
arr[i] = sc.nextInt();
}
System.out.print("Please enter a target value: ");
int target = sc.nextInt();
System.out.println(Arrays.toString(arr));
// Algorithm here.
}
}
import java.util.Scanner;
public class Exercise6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input first number: ");
int num1 = in.nextInt();
System.out.print("Input second number: ");
int num2 = in.nextInt();
System.out.println(num1 + " + " + num2 + " = " +
(num1 + num2));
System.out.println(num1 + " - " + num2 + " = " +
(num1 - num2));
System.out.println(num1 + " x " + num2 + " = " +
(num1 * num2));
System.out.println(num1 + " / " + num2 + " = " +
(num1 / num2));
System.out.println(num1 + " mod " + num2 + " = " +
(num1 % num2));
}
}
enter code here
''' Input first number: 32 Input second number: 12 19 + 1 = 20 32 - 12 = 20 9+11= 20'
Yes, it is possible to do it only in the main class. It is even possible to do it only in the main method (despite doing it an own method is better, easier to understand). Just two nested for loops; one for the first value, one for the second value. Inside the inner loop just test if the sum of both values result in the expected result, same for subtraction. Set a boolean to indicate that at least one case was found. At the end print the negative message if the boolean is not set.
Sample:
private static boolean findCombinations(int target, int[] values) { // or ,int... values) {
boolean found = false;
for (int i = 0; i < values.length; i++) {
// second loop
// tests and print
}
return found;
}
I'm wondering how to display the correct answer right after where it says "Your answer is wrong. The correct answer is " in the for loop in the method main(). My problem is that the variable for the answer isn't declared until the oneProblem() method.
package multiplicationquiz;
import static java.lang.System.out;
import java.util.Random;
import java.util.Scanner;
public class MultiplicationQuiz {
final static Scanner cin = new Scanner(System.in);
final static Random rand = new Random();
public static void main(String[] args) {
out.println("Welcome to the Multiplication Table Quiz\n");
out.print("Enter your given name (no spaces): ");
String name = cin.next();
out.println("\nGreetings, " + name + ". I will ask you 10 problems.");
out.println("Ready, set, go!");
int qno;
int numCorrect = 0, numProbs = 10;
for (qno = 1; qno <= 10; qno++){
if (oneProblem(qno) == true){
out.println("Your answer is correct!");
numCorrect ++;
}
else
out.println("Your answer is wrong. The correct answer is ");
} // end for
report(name, numProbs, numCorrect);
} // end main
static boolean oneProblem(int qno) {
int number1 = 1 + rand.nextInt(10), number2 = 1 + rand.nextInt(10);
out.print("\nProblem " + qno + ": What is " + number1 + " times "
+ number2 + "? ");
int answer = cin.nextInt();
if (answer == number1 * number2)
return true;
else
return false;
} // end oneProblem
static void report(String name, int numProbs, int numCorrect) {
out.print("Test report for " + name + "\n\n");
out.print("Problems attempted: " + numProbs + "\n");
out.print("Correct answers: " + numCorrect + "\n");
out.print("Incorrect answers: " + (numProbs - numCorrect) + "\n");
if (numCorrect == 10)
out.print("Congratulations! You got a perfect score.");
if (numCorrect < 10 && numCorrect >= 8)
out.print("You did all right.");
if (numCorrect < 8 && numCorrect >= 7)
out.print("You pass, but you should try to do better.");
if (numCorrect < 7)
out.print("You really need to study harder.");
} // end report
static int getInt(String prompt) {
out.print(prompt);
return cin.nextInt();
}
}
You need to find a way to return both the status (boolean) and the answer from your oneProblem() method.
One way of doing this is to use an abstract "problem" class and inheritance for each kind of problem.
There are also some nice design patterns to do so.
A problem class could look like :
public class problem {
private string answer; // could be of an abstract parent class
private boolean isTestPassed = false; // could be of an abstract parent class
private (sometype) solution; // this one of concrete class
public void askQuestion() { // could be defined at abstract parent class level
// compute solution
...
this.solution = // computed solution
// ask question and get answer
...
this.answer = // put user input in here
this.isTestPassed = (this.answer.equals(this.solution));
}
public getAnsswer(); // could be defined at abstract parent class level
public getSolution(); // could be defined at abstract parent class level
public getIsTestPassed(); // could be defined at abstract parent class level
}
With this, you can create as many kind of problems you like, and you can instanciate as many.
You have convenient methods to get user answers and the solutions.
You are able to define a list, table or any kind of collection of problems to improve or extend your software.
Of course, as showed in others answers, you have quite an infinite amount of possible solutions to just print the user input. See #Shashwat's answer
Make a static variable outside the main method as such :
public class Main {
final static Scanner cin = new Scanner(System.in);
final static Random rand = new Random();
static int ans = 0;
Now, in the oneProblem method, add this:-
ans = number1 * number2; //Add this Line
if (answer == number1 * number2)
return true;
else
return false;
Now, the correctAnswer is stored in ans. Now you can simply print it out:
out.println("Your answer is wrong. The correct answer is " + ans);
Given that it is a quiz, i'm asuming you are only trying to give 1 question at a time, if this is the case u can save the random variables on class scope
public class SomeClass{
private int ran1;
private int ran2;
public booleans somequiz(int in)
ran1 = random.nextInt();
ran2 = random.nextInt();
}
this will mean that at any given time the current quiz randoms are accessible, untill the quiz function is being called again and they are overwritten by the new random int's, but make sure that the ints are at some point assigned before you use them or it will return a nullpointer
public class SomeClass{
private int a;
public static main(String[] args){
System.out.Print(a); // a was never set thus nullpointer
}
}
oneProblem can return a result Object instead of boolean.
class result {
public result(boolean s, int n) { status = s; number = n; }
public boolean status;
public int number;
}
static result oneProblem(int qno) {
int number1 = 1 + rand.nextInt(10), number2 = 1 + rand.nextInt(10);
out.print("\nProblem " + qno + ": What is " + number1 + " times "
+ number2 + "? ");
int answer = cin.nextInt();
if (answer == number1 * number2)
return new result(true, number1 * number2);
else
return new result(false, number1 * number2);
}
and when you want to check:
result res = oneProblem(qno);
if (res.status == true){
out.println("Your answer is correct!");
numCorrect ++;
}
else
out.println("Your answer is wrong. The correct answer is " + res.number);
Add the logs in the oneProblem method itself
static boolean oneProblem(int qno) {
int number1 = 1 + rand.nextInt(10);
int number2 = 1 + rand.nextInt(10);
out.print("\nProblem " + qno + ": What is " + number1 + " times "
+ number2 + "? ");
int answer = cin.nextInt();
if (answer == number1 * number2) {
out.println("Your answer is correct!");
return true;
}else {
out.println("Your answer is wrong. The correct answer is " + (number1*number2));
return false;
}
}
I am trying to make the program end when total reaches 10, but for some reason my while loop continues counting when it reaches 10. I have the int percent to find the percent once 10 questions are answered.
import java.util.*;
class CAI {
private static Scanner input;
public static void main(String[] arguments) {
menu();// calls menu method
compute();// calls compute method
}
public static void menu() {// method that displays menu
System.out.println(" CAI MENU ");
System.out.println("\n)");
System.out
.println("\n1) DIFFICULTY 1\n2) DIFFICULTY 2\n3) DIFFICULTY 3\n4) DIFFICULTY 4");
}
public static int[] Blop() {
Random rand = new Random();
int arr[] = new int[8];
arr[0] = rand.nextInt(9);
arr[1] = rand.nextInt(9);
arr[2] = rand.nextInt(99);
arr[3] = rand.nextInt(99);
arr[4] = rand.nextInt(999);
arr[5] = rand.nextInt(999);
arr[6] = rand.nextInt(9999);
arr[7] = rand.nextInt(9999);
return arr;
}
public static void compute() {
int difficulty;
input = new Scanner(System.in);
System.out.println("Enter an option: ");
difficulty = input.nextInt();
int total = 0;
int percent = 0;
while (total <= 10) {
if (difficulty == 1) {
int num[] = new int[2];
int ans;
String choice;
do {
num = Blop();
do {
System.out.print("How much is " + num[0] + " times "
+ num[1] + " ? :");
total++;
System.out.print(total);
ans = input.nextInt();
String Correct;
String Wrong;
String[] correct = { "Very good! ", "Excellent! ",
"Nice work! ", "Keep up the good work! " };
String[] wrong = { "No. Please try again. ",
"Wrong. Try once more. ", "Don’t give up! ",
"No. Keep trying " };
Random rand = new Random();
Correct = correct[rand.nextInt(correct.length)];
Wrong = wrong[rand.nextInt(wrong.length)];
if (ans == (num[0] * num[1])) {
System.out.print(Correct);
percent++;
} else {
System.out.print(Wrong);
}
} while (ans != (num[0] * num[1]));
System.out.print("Do you want more questions(yes/no) :");
input.nextLine();
choice = input.nextLine();
} while (choice.equalsIgnoreCase("yes"));
}
}
if (difficulty == 2) {
int num[] = new int[2];
int ans;
String choice;
do {
num = Blop();
do {
System.out.print("How much is " + num[2] + " times "
+ num[3] + " ? :");
ans = input.nextInt();
String Correct;
String Wrong;
String[] correct = { "Very good! ", "Excellent! ",
"Nice work! ", "Keep up the good work! " };
String[] wrong = { "No. Please try again. ",
"Wrong. Try once more. ", "Don’t give up! ",
"No. Keep trying " };
Random rand = new Random();
Correct = correct[rand.nextInt(correct.length)];
Wrong = wrong[rand.nextInt(wrong.length)];
if (ans == (num[2] * num[3])) {
System.out.print(Correct);
} else {
System.out.print(Wrong);
}
} while (ans != (num[2] * num[3]));
System.out.print("Do you want more questions(yes/no) :");
input.nextLine();
choice = input.nextLine();
} while (choice.equalsIgnoreCase("yes"));
}
if (difficulty == 3) {
int num[] = new int[2];
int ans;
String choice;
do {
num = Blop();
do {
System.out.print("How much is " + num[4] + " times "
+ num[5] + " ? :");
ans = input.nextInt();
String Correct;
String Wrong;
String[] correct = { "Very good! ", "Excellent! ",
"Nice work! ", "Keep up the good work! " };
String[] wrong = { "No. Please try again. ",
"Wrong. Try once more. ", "Don’t give up! ",
"No. Keep trying " };
Random rand = new Random();
Correct = correct[rand.nextInt(correct.length)];
Wrong = wrong[rand.nextInt(wrong.length)];
if (ans == (num[4] * num[5])) {
System.out.print(Correct);
} else {
System.out.print(Wrong);
}
} while (ans != (num[4] * num[5]));
System.out.print("Do you want more questions(yes/no) :");
input.nextLine();
choice = input.nextLine();
} while (choice.equalsIgnoreCase("yes"));
}
if (difficulty == 4) {
int num[] = new int[2];
int ans;
String choice;
do {
num = Blop();
do {
System.out.print("How much is " + num[6] + " times "
+ num[7] + " ? :");
ans = input.nextInt();
String Correct;
String Wrong;
String[] correct = { "Very good! ", "Excellent! ",
"Nice work! ", "Keep up the good work! " };
String[] wrong = { "No. Please try again. ",
"Wrong. Try once more. ", "Don’t give up! ",
"No. Keep trying " };
Random rand = new Random();
Correct = correct[rand.nextInt(correct.length)];
Wrong = wrong[rand.nextInt(wrong.length)];
if (ans == (num[6] * num[7])) {
System.out.print(Correct);
} else {
System.out.print(Wrong);
}
} while (ans != (num[6] * num[7]));
System.out.print("Do you want more questions(yes/no) :");
input.nextLine();
choice = input.nextLine();
} while (choice.equalsIgnoreCase("yes"));
}
System.out.print(100 / 10 * percent);
}
}
Your while loop is declared:
"while total is less than or equal to ten"
which means it will run once again at 10.
just make it while total <10
edit: you also don't increment total anywhere.
total++;
will do it.
edit: it appears you do. sorry the code is hard to read on a phone.
There could be multiple reasons for this happening. One such reason is that if the variable difficulty does not equal one(this variable is nowhere to be found in your code also), then total will never be incremented, and as a result the first while loop will last forever. Because you have not shared all of your code, it could also be that ans != (num[0] * num[1] is never true, and as a result, the innermost do/while loop is executed forever. If you post the rest of your code, we will be able to assist you more.
EDIT: OK, thanks. It looks like your problem is due to the fact that while the user continues to get the question wrong, they cannot escape the inner while loop, therefore not being able to escape the outer while loop. The solution to that is easy, simply changing while (ans != (num[4] * num[5])); to ans != (num[0] * num[1]) && total < 10, thereby giving the code a way to escape while the user is getting the question wrong.
Sorry for probably a noobish question but I can't figure out what's wrong with this code. I've looked everywhere but I couldn't find any answer.
The problem is that it will only randomly generate num and num2 once when I need it randomly genereated 5 times. Any help is greatly appreciated.
import java.util.Scanner;
import java.util.Random;
public class Choice5
{
public static void main(String [] args)
{
Random r = new Random();
Scanner k = new Scanner(System.in);
String name;
int num= 1 + r.nextInt(10);
int num2=1 + r.nextInt(10);
int answer = num*num2;
int attempt;
int countcorrect = 0;
int countincorrect =0;
System.out.println("Hi, what's your name?");
name =k.next();
for(int x=1; x<=5; x++)
{
System.out.println("Test " +x+ " of 5");
System.out.println("Ok " +name+ " What is " +num+ " x " +num2+ " ?");
attempt = k.nextInt();
if(attempt == answer)
{
System.out.println("Good Job " +name+ " the answer was indeed " +answer);
countcorrect++;
}
if(attempt != answer)
{
System.out.println("Incorrect " +name+ " the answer was actually " +answer);
countincorrect++;
}
}
System.out.println("You got " +countcorrect+ " right");
System.out.println("You got " +countincorrect+ " wrong");
if (countcorrect < 3)
{
System.out.println("You should try the test again");
}
else
{
System.out.println("Good job " +name+ " ,you passed the test!");
}
}
}
You are choosing random numbers for num and num2 exactly once, toward the top of main, and more importantly, before the for loop. These numbers aren't assigned again, so they remain the same during all loop iterations.
To have them change for each loop iteration, declare the variables for the numbers and the answer, and assign new values inside the for loop, instead of before it.
for(int x=1; x<=5; x++)
{
int num= 1 + r.nextInt(10);
int num2=1 + r.nextInt(10);
int answer = num*num2;
// rest of code is the same
You generate a random number when, in this case, you call nextNum() As you can see you only call this once for num and num2 since it is out of the loop.
Simple answer, put those calls within your loop to create more than one random number.
I basically want to be able to loop an X + Y = Z equation until the user inputs something other than an integer, like the letter "A" and also when having any number make the loop stop displaying a message.
Also, I am confused on how to randomly position the "?" which the user must input the correct answer.
For example
System.out.println("What is: " + num1 + " + ? = " + answer);
So far:
I am positioning the "?" manually through the IF statements. Can this be done in a more efficient way?
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int num1, num2, number3, answer;
do {
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println("What is: " + num1 + " + ? = " + answer);
number3= input.nextInt();
if (number3 == num2)
System.out.println("That is correct");
else
System.out.println("That is wrong");
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println(num1 + " + ? = " + answer);
number3= input.nextInt();
} while(number3 !=0);
}
Here is one way to do it:
public static void main(String[] args) {
Random rand = new Random();
Scanner scanner = new Scanner(System.in);
int[] xyz = new int[3];
String[] display = new String[3];
int answer, position;
do {
xyz[0] = 1 + rand.nextInt(10);
xyz[1] = 1 + rand.nextInt(10);
xyz[2] = xyz[0] + xyz[1];
for (int i = 0; i < xyz.length; i++)
display[i] = String.valueOf(xyz[i]);
position = rand.nextInt(3);
display[position] = "?";
System.out.println("What is: " + display[0] + " + " + display[1] + " = " + display[2]);
do {
System.out.println("Please enter an integer or 'S' to stop");
String input = scanner.nextLine();
if (input.equals("S")) {
scanner.close();
System.out.println("Stopped");
return;
}
else if (input.matches("\\d+")) { // \\d+ means "a digit (0-9) once or more
answer = Integer.parseInt(input);
break;
}
} while (true);
if (answer == xyz[position])
System.out.println("That is correct");
else
System.out.println("That is wrong");
} while (true);
}
Notes:
I use an inner do-while loop to repeatedly check the input and ask the user for a valid input.
I use 2 arrays: one for storing the numbers and another for storing the display values.
I also added a stop condition since the outer loop is infinite. Always close the Scanner when you finish.
I randomly pick 1 of 3 positions for the "?".