Rerun Main method from Main Method - java

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

Related

How to repeat a question to a user until while loop condition is false?

I'm bulding a console application where I am trying to force a user to enter an int as a possible answer to a question otherwise the same question is repeated to the user.Thus, the user cannot move on without entering the proper data type.
below is my sample code.
Scanner scanner = new Scanner(System.in);
int userInput = 0;
do {
AskQuestion();
if(scanner.hasNextInt()) {
userInput = scanner.nextInt();
}
}
while(!scanner.hasNextInt()) ;
While I know this can be done in C#, I'm not exactly sure how to do it in java without getting stuck in an infinite loop. How do I get my code to do what I want to do? Please help!
You can use something like this. It'a a pretty simple flag combined with the use of the Scanner class.
boolean flag = false;
int val = 0;
while(!flag){
System.out.println("Something");
if(sc.hasNext()){
if(sc.hasNextInt()){
val = sc.nextInt();
flag = true;
}
else{
sc.next();
}
}
}
Try this:
Scanner scanner = new Scanner(System.in);
int userInput;
while(true) {
AskQuestion();
if (scanner.hasNextInt()) {
userInput = scanner.nextInt();
break;
}
scanner.next(); // consume non-int token
}
Another alternative which utilizes the Scanner#nextLine() method along with the String#matches() method and a small Regular Expression (RegEx) to ensure that the supplied string does indeed contain all numerical digits:
Scanner scanner = new Scanner(System.in);
String userInput = "";
int desiredINT = 0; // Default value.
while (desiredINT == 0) {
AskQuestion();
userInput = scanner.nextLine();
if (userInput.matches("\\d+")) {
desiredINT = Integer.parseInt(userInput);
if (desiredINT < 1 || desiredINT > 120) {
System.out.println("Invalid Input! The age supplied is not "
+ "likely! Enter a valid Age!");
desiredINT = 0;
}
}
else {
System.out.println("Invalid Input! You must supply an Integer "
+ "value! Try Again...");
}
}
System.out.println("Your age is: --> " + desiredINT);
And the AskQuestion() method:
private void AskQuestion() {
System.out.println("How old are you?");
}
This is nice and short one
Scanner scanner = new Scanner(System.in);
do askQuestion();
while(!scanner.nextLine().trim().matches("[\\d]+"));
Tell me if you like it
Note it just tell you if number was an int , and keeps repeating if not, but doesn't give you that int back , tell me if you need that, i shall find a way
My solution might be a bit bloated, but I hope it's nice and clear what's going on. Please do let me know how it can be simplified!
import java.util.Scanner; // Import the Scanner class
class Main {public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String unit;
// unit selector
while (true) {
System.out.println("Did you measure ion feet or meters? Type 'meters' or 'feet': ");
String isUnit = myObj.nextLine();
if (isUnit.equals("feet") || (isUnit.equals("meters"))) {
unit = isUnit;
break;
} else {
System.out.println("Please enter either 'meters' or 'feet'.");
}
}
System.out.println("Use selected " + unit);
}

Writing program to help elementary students learn multiplication

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.

Break a programm with a loop

I wrote a code which calculates grades. But if I'm typing 9999 in the console, then the program should break without any output. How can I do this and which loop should I use? I tried it with a while loop but the program gives me still output.. this is my code with the while loop which doesn't work as it should. The Programm works except for the while loop. How can I do write this better?
import java.util.Scanner;
public class average {
public static double average (double [] grade ){
double sum = 0;
int number = grade.length;
for(int i = 0; i<grade.length; i++){
sum+=grade[i];
}
double average = sum / number;
return average;
}
public static void main (String [] args){
Scanner s = new Scanner(System.in);
System.out.println("How much grades you add?");
int number = s.nextInt();
while(number == 9999){
break;
}
double [] grade = new double [number];
System.out.println("Please enter : ");
for(int i = 0; i<grade.length; i++){
grade[i] = s.nextDouble();
}
System.out.println("My grades are: ");
for(int i = 0; i<grade.length; i++){
System.out.println(grade[i] + " | ");
}
System.out.println("");
System.out.println("My average: " +average(grade));
}
}
You are using a break, which immediately exits only the loop. If you want to quit the program, you should use if and return like this:
if(number == 9999) {
return;
}
This quits the program because with return, you exit the current function. The current function is main(), that's the program's main code. So, if you exit it, you will quit the program.
In functions with a return value (non-void functions) you need to specify the return value like this:
return 9999;
If you are on an other program thread, you need to call System.exit(0).
You don't need to break any loop, you just need to exit the program.
if (number == 9999) {
System.exit();
}

Multiplication Tutor Java Program

I am working on writing a program that follows these instructions:
Your little sister asks you to help her with her multiplication, and you decide to write a Java program that tests her skills. The program will let her input a starting number, such as 5. It will generate ten multiplication problems ranging from 5×1 to 5×10. For each problem she will be prompted to enter the correct answer. The program should check her answer and should not let her advance to the next question until the correct answer is given to the current question.
After testing ten multiplication problems, your program should ask whether she would like to try another starting number. If yes, your program should generate another corresponding ten multiplication problems. This procedure should repeat until she indicates no.
I have the code correct to ask for the multiplication part, but I can't quite figure out how to get the program to ask if the user wants to continue.
The following code has the program run through once:
package hw5;
import java.util.Scanner;
public class HW5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number you would like to attempt: ");
int start = input.nextInt();
int mult;
for (mult = 1; mult <= 10; mult++) {
int num = start * mult;
System.out.print(start + " x " + mult + " = ");
int ans = input.nextInt();
while (ans != num) {
System.out.print("Wrong answer, try again: ");
int ans2 = input.nextInt();
if (ans2 == num) {
break;
}
}
//System.out.print("Would you like to do another problem? ");
}
}
}
When I uncomment out line 21 the program returns:
Enter number you would like to attempt: 1
1 x 1 = 1
Would you like to do another problem? 1 x 2 = 2
Would you like to do another problem? 1 x 3 =
etc...
If I take the code from line 21 and put it outside of the for loop the program runs the for loop once and then jumps straight to the question.
How do I go about fixing this and successfully completing the instructions?
Here's how I'd do it:
package hw5;
import java.util.Scanner;
public class HW5 {
public static void main(String[] args)
{
boolean wantsToContinue = true;
while(wantsToContinue)
{
wantsToContinue = mathProblem();
}
}
public static boolean mathProblem()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter number you would like to attempt: ");
int start = input.nextInt();
int mult;
for (mult = 1; mult <= 10; mult++) {
int num = start * mult;
System.out.print(start + " x " + mult + " = ");
int ans = input.nextInt();
while (ans != num) {
System.out.print("Wrong answer, try again: ");
int ans2 = input.nextInt();
if (ans2 == num) {
break;
}
}
//System.out.print("Would you like to do another problem? ");
}
boolean wantsToContinue;
//Ask if the user would like to do another problem here, set "wantsToContinue" accordingly
return wantsToContinue;
}
}

Java method won't return answer in my LCM program

So what this program does is take two numbers as input using the Scanner class, and calculates the lowest common multiple of those two numbers. Everything seems to be working, except the lcm method won't return anything. I may have messed something up with my 'break' statements, but I didn't know any other way to get out of the if statement that is nested in a while loop. One more question: Is using a while(True) loop good practice or bad practice? Because I've seen lots of mixed opinions on it. If anyone has any better alternatives to while(True) loops I'd be happy to hear them. Thank you!
// LCM Calculator
// Author: Ethan Houston
// Language: Java
// Date: 2013-12-27
import java.io.*;
import java.util.Scanner;
public class lcm {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("This is a LCM calculator\n");
System.out.println("Enter your first number: ");
int firstNumber = scanner.nextInt();
System.out.println("Enter your second number: ");
int secondNumber = scanner.nextInt();
lcm(firstNumber, secondNumber);
}
public static int lcm(int one, int two) {
int counter = Math.min(one, two);
int initialCounter = counter;
boolean running = true;
while (running) {
if (counter % one == 0 && counter % two == 0) {
break;
} else {
counter += initialCounter;
}
}
return counter;
}
}
You do return something, you're just not printing it. Just try:
System.out.println(lcm(firstNumber, secondNumber));
You are not printing the returned value
System.out.println(lcm(firstNumber, secondNumber));
As you had written,
lcm(firstnumber, secondnumber);
this method will return an int type value, but in your code, you are not obtaining the returned value in any variable.
So, you should write like this :
int variable=lcm(firstnumber, secondnumber);

Categories