Write a program that will help an elementary school student learn multiplication. Use a SecureRandom object to produce two positive one-digit integers (you will need to look up how to do this). The program should then prompt the user with a question, such as
How much is 6 times 7? The student then inputs the answer. Next, the program checks the student’s answer. If it’s correct, display the message "Very good!" and ask another multiplication question. If the answer is wrong, display the message "No. Please try again.>again." and let the student try the same question repeatedly until the student finally gets it right.
A separate method should be used to generate each new question. This method should be called once when the application begins execution and each time the user answers the question correctly.
My question is do you have to make an if else statement == my public static mathQuestion and then have it output? I am lost on what to do after making the SecureRandom. I'm still new to Java.
I've tried doing an if-else statements after missing the question more than once but it has be done in a method.
import java.security.SecureRandom;
import java.util.;
public class h_p1 {
static SecureRandom rand = new SecureRandom();
static Scanner sc = new Scanner (System.in);
public static int mathQuestion() {
int n1 = rand.nextint(9) + 1;
int n2 = rand.nextint(9) + 1;
System.out.print("What is" + n1 + "x" + n2"?");
return r1 * r2;
}
}
}
You need to do the following:
Prompt for the answer
Check the answer by using an if statement.
If the answer is incorrect, prompt again.
If it correct, generate another question.
You will need to use loops in this situation. It could take on
different designs but you would need one for the reprompting and one for
the new question.
Imo, the best way to do the reprompting is to use a while statement with a settable boolean value. If they get the answer correct, set the boolean to false
otherwise, keep prompting while true. You could also use a for loop if you want to limit the number of guesses.
public class Quiz {
public static void main(String[] args) {
generateRandomNumbers();
}
public static void generateRandomNumbers() {
SecureRandom rand = new SecureRandom();
Scanner sc = new Scanner (System.in);
int n1 = rand.nextInt(9) + 1;
int n2 = rand.nextInt(9) + 1;
generateQuestion(n1,n2);
}
public static void generateQuestion(int n1, int n2) {
Scanner sc = new Scanner (System.in);
System.out.print("What is " + n1 + " x " + n2+ " ?");
int typedAnswer = sc.nextInt();
if(typedAnswer == (n1*n2)) {
System.out.println("Correct Answer");
generateRandomNumbers();
}else {
System.out.println("Wrong Answer");
generateQuestion(n1,n2);
}
}
}
The simplest answer to this question that I could have thought for:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
SecureRandom secureRandom = new SecureRandom();
int numbOne = secureRandom.nextInt(9) + 1;
int numbTwo = secureRandom.nextInt(9) + 1;
int prod = numbOne * numbTwo;
int response;
do {
System.out.println(MessageFormat.format("What is the product of {0} and {1}", numbOne, numbTwo));
response = scanner.nextInt();
if (response != prod) {
System.out.println("Incorrect answer! Try again");
}
} while (response != prod);
System.out.println("Correct answer");
System.out.println("Do you want to practice with another question (Y/N)?");
} while (scanner.next().equalsIgnoreCase("Y"));
}
It uses 2 do-while loops. The outer loop controls the number of times a question should be asked depending on user's choice and the inner loop checks the correctness of the answer given by the user.
Related
I need a help trying to set my code to continuously receive user input for factorial numbers. It will produce a question and intake the user input but only once. I want it to continue asking the user for that input.
I tried to do a while loop however nothing shows up.
import java.util.Scanner;
public class FactorialRecursion
{
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
long userInput;
System.out.println("Please enter a number you would like find the factorial of.");
userInput = scan.nextLong();
long fc = FactorialRecursion.fact(userInput);
System.out.println("Factorial = " + fc);
}
public static long fact(long x)
{
if (x <= 0)
return 1;
else
return FactorialRecursion.fact(x - 1) * x;
}
}
The output is correct but I want my program to continue asking for that input.
public class Test{
public static void main(String []args) {
int num;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter numbers!");
while((num = scanner.nextInt()) > 0) {
System.out.println("Receiving...");
}
{
System.out.println("Negative number Stopping the system...");
System.exit(1);
}
}
}
Without knowing how you were looping before (my assumption is that you were including the scanner instantiation which might have caused an issue), here is an implementation that I believe will work for you. This will continue to scan for a number, unless a negative number is entered. Therefore you have an actual exit condition that doesn't make sense for factorial, and the user can repeatedly enter and find the factorial of positive numbers.
In order for this to work, I instantiated the userInput variable to be 0 so that the loop will run for the first time. You can alteratively use a do...While loop in stead, but I prefer this method generally.
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
long userInput=0;
while(userInput >=0)
{
System.out.println("Please enter a number you would like find the factorial of. Enter a negative number to exit.");
userInput = scan.nextLong();
long fc = FactorialRecursion.fact(userInput);
System.out.println("Factorial = " + fc);
}
}
If you would like to see what the do-while loop would look like, just comment and I'll put a little more time into answering this. Also any questions you have comment away!
I have a program that will help the user to learn a multiplication table and then show results of right/wrong answers. The first step is to simply ask the user for which multiplication table it want to work on (1-9). And then the user will get a random sequence of number multiplied by the chosen multiplication table. If the user answers correctly then that number won't be shown again, but if incorrectly then it will be shown until the correct answer is made.
One scenario could be that the user chooses "3", and it will then be displayed in a random sequence such as (3x7 =, 3x1 =, 3x9 =...). And the user will answer after each "=". Right now, I can only print it all in ascending order, should I use Random multiplied with the chosen table in a while loop instead?.
My second issue, is how I can ask the incorrectly answered numbers again, until correctly answered? Am I right to think that a for loop isn't the best choice in this case?
Here is my code so far:
public class Multiplication {
public static void main (String[] args) {
Scanner inread = new Scanner (System.in);
int answer;
System.out.println("Choose multiplication table (1-9)");
int num1= inread.nextInt();
for (int i=1; i<11; i++) {
System.out.println("Write answer after = ");
System.out.println(num1 + " x " + (i) + " = ");
answer=inread.nextInt();
if (answer == (num1 * i) ) {
System.out.println("Correct answer");
// Do not show that number again
}
else {
System.err.println("Wrong answer");
//Show this number again.
}
}
}
}
New code after int num1 = inread.nextInt();
unanswered.add(1);
unanswered.add(2);
unanswered.add(3);
unanswered.add(4);
unanswered.add(5);
unanswered.add(6);
unanswered.add(7);
unanswered.add(8);
unanswered.add(9);
unanswered.add(10);
Collections.shuffle(unanswered);
while (!unanswered.isEmpty()) {
System.out.println(num1 + "*" + "unanswered" + " = "); //?
answer = inread.nextInt();
if (answer == (num1 * unanswered)) { //?
unanswered.remove(unanswered); //?
}
}
So, I think this is almost the way you suggested? However I'm sure I could add the numbers in a more beautiful way. I am used to looping through lists with a for loop in order to then use the counter to display the list. So where I putted a "?" is because I am not sure how to specify where in the list I am trying, for example to remove a number.
Or should I have the while loop, inside the for loop that I originally had? So that I could use the (i) in the for loop to specify where in the list I will display and perhaps remove?
A good question and a good start on the coding.
One way of asking for input until all the multiplication questions have been solved would be a while loop.
As #Easton pointed out an ArrayList to store the numbers and Collections.shuffle will help with the setup. By creating the ArrayList ahead of time then using a while loop until it is empty to prompt the user to keep answering.
EDIT
Heading in the right direction. To simplify the creation of unanswered numbers make use of the for loop, Something like: for(i=1, i<=10,i++) then add(i) to unanswered.
In the while loop, grab the first index: unanswered[0] and set that to num1 then if the answer is correct, remove it (as you have now). If not use Collections.rotate on unanswered by 1. Which will move the unanswered question to the end of the array for another attempt later.
Bellow you can find a solution for your problem with Hash Tables, you can do modifications to it so that the user can not type a number larger than 9 or smaller than 0 but this should work for your purpose:
import java.util.Random;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Multiplication {
public static void main (String[] args) {
Map<Integer, Integer> list = new HashMap<Integer, Integer>();
Scanner inread = new Scanner (System.in);
int answer;
System.out.println("Choose multiplication table (1-9)");
int num1= inread.nextInt();
for (int i = 1; i<10; i++) {
list.put(i, num1*i);
}
System.out.println(list);
while (!list.isEmpty()) {
System.out.println("Write answer after = ");
Random generator = new Random();
Object[] keys = list.keySet().toArray();
Object randomValue = keys[generator.nextInt(keys.length)];
int next = (Integer) randomValue;
System.out.println(num1 + " x " + (next) + " = ");
answer=inread.nextInt();
if (answer == (num1 * next)) {
System.out.println("Correct answer");
list.remove(next);
} else {
System.err.println("Wrong answer");
}
}
System.out.println("Congrats!!!");
}
}
I'm trying to come up with a reverse guessing game. Computer to guess my selected number with a range of 1-100. I do have the binary search algorithm, but when I tell the computer it's first guess is Too High, it will give me another High guess instead of going lower.
import java.util.Random;
import java.util.Scanner;
public class ComputersGuessGame {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random value = new Random();
int computerGuess;
int highValue = 100;
int lowValue = 1;
String myAnswer;
do {
computerGuess = value.nextInt(highValue - lowValue +1)/2;
/*
*Above line should use the binary algorithm so the computer can
*make guesses and not just guess my number by going one number at a time
*/
System.out.println("I'm guessing that your number is " + computerGuess);
myAnswer = in.nextLine();
if (myAnswer.equals("tl")){
highValue = computerGuess + 1;//Too Low Answer
}
else if (myAnswer.equals ("th")){
lowValue = computerGuess - 1;//To High Answer
}
} while (!myAnswer.equals("y")); //Answer is correct
in.close();
System.out.println("Thank you, Good Game.");
}
}//Comptuer keeps making random guesses, but if I say too high, it will guess another high number instead of going low.
I think your logic to guess the next number was wrong. You should have interchange the setting the lower & high value,and change the logic to generate next guess.
here is the working solution of your problem
import java.util.Random;
import java.util.Scanner;
public class Guess {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random value = new Random();
int computerGuess;
int highValue = 100;
int lowValue = 1;
String myAnswer;
do {
computerGuess = value.nextInt(highValue - lowValue)+lowValue;
System.out.println("I'm guessing that your number is " + computerGuess);
myAnswer = in.nextLine();
if (myAnswer.equals("tl")){
lowValue = computerGuess + 1;
} else if (myAnswer.equals ("th")){
highValue = computerGuess - 1;
}
} while (!myAnswer.equals("y"));
in.close();
System.out.println("Thank you, Good Game.");
}
}
you should try to approximate to your guess. you should try nested intervals. your working with class random, of course your computer could guess another high number again, when only lowering the range by one.
you should work with at least 2 new variables, rangeLow and rangeHigh. when to high, your new rangeHigh is your last guess. when to low, your new rangeLow is your last guess.
computerGuess = value.nextInt(rangeLow,rangeHigh);
First off, yes this a HW assignment. Having issues with recursive factorials in Java. Everything I'm finding on here and elsewhere already shows me what I've done is correct. However I'm having issues with an additional step. Basically what I need is the 1) User to enter a number 2) Factorial to be calculated 3) If user enters anything but a character or string (rather than an int) for an error message to come out 4) The question to repeat until user enters "0" to exit.
Steps 1 and 2 I have completed. I'm having issues with step 3. It seems like I am missing a return statement if the user enters anything but an int but I can't seem to figure out exactly what.
Here is code thus far:
import java.util.Scanner;
public class Recursive
{
public static void main(String[] args)
{
int number; // To hold a number
char letter; // To hold a character
//Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
number = keyboard.nextInt();
//Display the factorial
System.out.println(number + "! is " + factorial(number));
}
private static int factorial(int n)
{
if (n == 0)
return 1; // Base Case
else if (n > 0)
return n * factorial(n-1);
else (!(n>0))
return
System.out.println(number + "is invalid");
}
}
After getting the user input, before doing factorial, we have to check if input is a number or not. We can use pattern. Check regular expression patterns to do that. After checking if it is a number or not, check if it is zero, if yes use exit (0) to come out of the program. If not do the factorial
while (true) {
// Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
int number = keyboard.nextInt();
if (Pattern.matches("\\d+", String.valueOf(number))) {
if (Integer.valueOf(number) == 0)
System.exit(0);
// Display the factorial
System.out.println(number + "! is " + factorial(number));
}
else
System.out.println("Error");
}
My answer is based on an assumption that your factorial function is working properly.In order to complete your step 3 and 4 you need to take input in a loop. In that loop, take input as string and parse it into integer, use try catch so that you can catch exception when a non-integer is given as input and you can prompt an error message.
public static void main(String[] args)
{
Integer number; // To hold a number
String letter; // To hold a character
//Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
while(keyboard.hasNext()){
letter = keyboard.next();
try{
number = Integer.parseInt(letter);
if(number==0){
//Exiting
break;
}
int fact = factorial(number);
//Display the factorial
System.out.println(number + "! is " + fact);
System.out.print("Enter an integer to find the factorial: ");
}
catch(NumberFormatException e){
System.out.println("Invalid input please enter integers only");
}
}
}
Also your factorial function is having compilation issues currently. You need to fix it for proper functioning of your code.
My solution for recursive factorial using Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.*;
import java.util.*;
class Main {
public static String factorial(int n,String s){
if(n>0){
BigInteger fact = new BigInteger(s);
fact = fact.multiply(new BigInteger(n + ""));
return factorial(n-1,fact.toString());
}
else{
return s.toString();
}
}
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int n = Integer.parseInt(line);
if(n==0)
System.out.println("Factorial is 0");
else{
String s = factorial(n,"1");
System.out.println("Factorial is " + s);
}
}
}
the example of factorial using recursive in Java
public class MainClass {
public static void main(String args[]) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("%d! = %d\n", counter,
factorial(counter));
}
}
public static long factorial(long number) {
if (number <= 1)
return 1;
else
return number * factorial(number - 1);
}
}
Basically the last thing I need to do for this Math Quiz I have to program, I have to ask the user if they would like to answer more problems, if yes, rerun everything in the Main Method. If no, print goodbye. The no is easy, but I'm unsure how to tell it to rerun the main method if they say yes. Here is the code in my main method.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int digit = 0;
String result1 = getUserChoice("");
digit = getNumberofDigit1(digit);
int numberOfProblems = amountOfProblems();
for (int i = 0; i < numberOfProblems; i++) {
int number1 = getRandomNumber1(digit);
int number2 = getRandomNumber2(digit);
System.out.println("Enter your answer to the following problem: \n" +
number1 + result1 + number2);
int correctAnswer = getCorrectAnswer(number1, result1, number2);
int userAnswer = getUserAnswer();
CheckandDisplayResult(correctAnswer, userAnswer);
}
System.out.println("Would you like to solve more probelms(Y/N)? ");
String moreProblems = in.next();
if ("Y".equals(moreProblems)){
digit = 0;
result1 = getUserChoice("");
digit = getNumberofDigit1(digit);
numberOfProblems = amountOfProblems();
for (int i = 0; i < numberOfProblems; i++) {
int number1 = getRandomNumber1(digit);
int number2 = getRandomNumber2(digit);
System.out.println("Enter your answer to the following problem: \n" +
number1 + result1 + number2);
int correctAnswer = getCorrectAnswer(number1, result1, number2);
int userAnswer = getUserAnswer();
CheckandDisplayResult(correctAnswer, userAnswer);
}
System.out.println("Would you like to solve more probelms(Y/N)? ");
moreProblems = in.next();
if ("Y".equals(moreProblems)){
}
System.out.println("Thank you for taking this quiz, Goodbye!");
}
Now I have tried something like,
if "Y".equals(moreProblems)){
copy and past the main method
}
But that has the error of requiring an infinite loops as you'd have to have the more problems statement in every if of yes, meaning it would never end coding wise, you would keep copying and pasting forever.
You could enclose all the code you want to "re-run" in a while loop:
boolean run = true;
while (run) {
// Here your code
// Here input if user want to re-run
if (getUserChoice("").equals("NO"))
run = false;
}
Alternative to what others have suggested, this is the method I prefer:
while(true) {
//do all your stuff
if(/*some exit condition*/) { break; }
}
What you can do is move everything in main() into another static method, call it interact(). Then in main(), just have logic which calls interact() as long as the user wants to interact with your program. In other words, put the math quiz into one method, and the business of presenting the quiz into main(). Your program will be easier to read and easier to modify further, if needed.
Put all of it in a big do-while loop:
boolean more = false;
do {
// all your code
more = "Y".equals(moreProblems);
} while (more);
Or provided your Scanner is declared outside the loop you can just:
do {
// all your code
} while ("Y".equals(in.next()));
I guess this prototype might help you
import java.util.Scanner;
public class MathsClass {
public static void main(String[] args){
MathsClass object = new MathsClass();
while(object.response())
object.mathsQuiz();
}
public void mathsQuiz(){
//your quiz functionalities
System.out.println("Add two nos");
}
public boolean response(){
System.out.println("Would u like to solve more problems? ");
Scanner scanner = new Scanner(System.in);
boolean response = scanner.nextBoolean();
return response;
}
}