Limit Repeating Addition Quiz- While loop - Java - java

I am trying to code in Java and started with a basic repeating addition quiz.
Repeating addition until enter the correct answer works fine, however, when I try to limit it to 3 trials, it does not stop at 3, but goes for 4 trials as shown below,
import java.util.Scanner;
public class RepeatAdditionQuiz {
public static void main(String[] args) {
// TODO Auto-generated method stub
int number1 = (int) (Math.random() * 10);
int number2 = (int) (Math.random() * 10);
Scanner input = new Scanner(System.in);
System.out.print("What is " + number1 + " + " + number2 + " : " );
int answer = input.nextInt();
int count = 0;
while(count < 3) {
if (number1 + number2 != answer) {
System.out.print("Try again, What is " + number1 + " + " + number2 + " : " );
answer = input.nextInt();
}
else
System.out.println("You're correct ");
count ++;
}
System.out.println("Your trails ended ");
}
}
This is my output,
What is 1 + 2 : 8
Try again, What is 1 + 2 : 6
Try again, What is 1 + 2 : 9
Try again, What is 1 + 2 : 9
Your trails ended
As you can see I have four trails with the first one. When I tried to remove first user input before while loop (which prints What is 1 + 2 :), I don't see anything in console. How can I just limit it to 3?
In python I can do something like this,
from random import randint
number1 = randint(0,9)
number2 = randint(0,9)
answer = number1 + number2
count = 0
while count < 3:
print(number1, "+", number2)
user_answer = int(input("What is number1 + number2: "))
if answer == user_answer:
print("yes, you're right")
break
else:
print("You're wrong, please enter again")
count +=1
print("Sorry, all trials are done! ")
And I get the output like this, exactly three trails (every time I enter wrong answer),
8 + 5
What is number1 + number2: 16
You're wrong, please enter again
8 + 5
What is number1 + number2: 18
You're wrong, please enter again
8 + 5
What is number1 + number2: 18
You're wrong, please enter again
Sorry, all trials are done!
What mistake am I making in java? Is there any better way to do in while loop? Any suggestion would be appreciated.

I prefer to use do-while loop in situation like this
import java.util.Scanner;
public class RepeatAdditionQuiz {
public static void main(String[] args) {
// TODO Auto-generated method stub
int number1 = (int) (Math.random() * 10);
int number2 = (int) (Math.random() * 10);
Scanner input = new Scanner(System.in);
System.out.print("What is " + number1 + " + " + number2 + " : ");
int answer = input.nextInt();
int count = 1;
do {
if (number1 + number2 != answer) {
System.out.print("Try again, What is " + number1 + " + " + number2 + " : ");
answer = input.nextInt();
} else{
System.out.println("You're correct ");
break;
}
count++;
} while (count < 3);
System.out.println("Your trails ended ");
}
}
In this I initialize count as 1 because we already provide answer an input at the time of instantiation.

You can change your main method to be something like Below. Basically it is your code with change suggested by Dave and a break statement in else block.
Hope this helps
public static void main(String[] args) {
// TODO Auto-generated method stub
int number1 = (int) (Math.random() * 10);
int number2 = (int) (Math.random() * 10);
Scanner input = new Scanner(System.in);
System.out.print("What is " + number1 + " + " + number2 + " : " );
int answer = input.nextInt();
int count = 0;
while(count < 2) {
if (number1 + number2 != answer) {
System.out.print("Try again, What is " + number1 + " + " + number2 + " : " );
answer = input.nextInt();
}
else{
System.out.println("You're correct ");
break;
}
count ++;
}
System.out.println("Your trails ended ");
}

The problem with your code is initially you are asking to guess the answer and then initializing the count as 0.
int answer = input.nextInt();
int count = 0;
You have already asked user for the 1st trail,so initialize count as 1.
int count = 1;
Another way to solve these kind of problems is to use do-while as mentioned by #Ayush Goyal.

To be close to your Python example you can try something like this
public static void main(String[] args) {
// TODO Auto-generated method stub
int number1 = (int) (Math.random() * 10);
int number2 = (int) (Math.random() * 10);
Scanner input = new Scanner(System.in);
int answer = 0;
int count = 0;
while(count < 3) {
System.out.print("What is " + number1 + " + " + number2 + " : " );
answer = input.nextInt();
if (number1 + number2 != answer) {
System.out.println("You're wrong, please enter again");
}
else{
System.out.println("You're correct ");
break;
}
count ++;
}
System.out.println("Your trails ended ");
}

Related

How can I find the multiple of two numbers using Java Modulus

This is the code that I have so far. I just want to know if I'm correct. I am very new to this and most likely I'm correct but I still wanted to know. thanks
Scanner input = new Scanner(System.in);
//variables
int number1;
int number2;
System.out.println("enter first number: ");
number1 = input.nextInt();
System.out.println("enter first number: ");
number2 = input.nextInt();
int multiple = number1 % number2;
if((number1 % number2) == 0) {
System.out.println("Yes, " + number1 + " is a multiple of " + number2);
}
else {
System.out.println("No, " + number1 + " is not a multiple of " + number2);
}
System.out.println("The multiple is: " + multiple);
}
I guess you want if a number is divisible by other or not and want to get multiplier if so.
Scanner input = new Scanner(System.in);
//variables
int number1;
int number2;
System.out.println("enter first number: ");
number1 = input.nextInt();
System.out.println("enter second number: ");
number2 = input.nextInt();
if((number1 % number2) == 0) {
System.out.println("Yes, " + number1 + " is a multiple of " + number2);
System.out.println("The multiple is: " + (number1 / number2));
}
else {
System.out.println("No, " + number1 + " is not a multiple of " + number2);
}
Your code works fine. But if you consider couple of things here it would be good.
Change your second prompt to "enter second number"
Currently you are printing message "The multiple is: " every time whether you find multiple or not.
So print this message only when you found a multiple. Move this line to if block to achieve this.

The program doesn't end when the timer ends until you give an input

I had some free time and I decided to make a program that could give me math questions using Java Eclipse. Whenever the timer ends during it though, the while loop doesn't end until you give one last input. I know that it is because of the while loop, but I don't know how to end it.
import java.util.Random;
import java.util.Scanner;
public class math_questioner_4 {
public static void main(String[] args) {
int firstnumber,secondnumber,operation,answer,answerinput,correctcount = 0,incorrectcount = 0, time, difficulty, max = 0, mixedop;
Scanner input;
System.out.println("What do you want the operation to be? 1 = addition 2 = subtraction 3 = multiplication 4 = division 5 = mixed");
input = new Scanner(System.in);
operation = input.nextInt();
// There is around 30 lines that don't relate to the question here
if (operation == 1) {
long endTime = System.currentTimeMillis() + (time*1000);
while (System.currentTimeMillis() < endTime) {
Random rand = new Random();
firstnumber = rand.nextInt(max) + 1;
secondnumber = rand.nextInt(max) + 1;
answer = firstnumber + secondnumber;
System.out.println("What is " + firstnumber + " + " + secondnumber + "?");
answerinput = input.nextInt();
if (answerinput == answer) {
System.out.println("Correct!");
correctcount++;
} else {
System.out.println("Sorry, " + firstnumber + " + " + secondnumber + " is " + answer + ".");
incorrectcount++;
}
}
// Another 140 lines here that don't matter either, just some operations
if (time == 1) {
System.out.println("You got " + correctcount + " questions correct and " + incorrectcount + " wrong in " + time + " second!");
} else {
System.out.println("You got " + correctcount + " questions correct and " + incorrectcount + " wrong in " + time + " seconds!");
}
}
}
I know that it's because of the while loop that it won't end, but I don't know how. Also please don't yell at me. I'm a beginner that takes classes at my Chinese school, it's only my 9th week (I've been to nine classes) and this is random extra stuff. I get most of my answers from this website and I also have only learned to do things with integers. It's also my first question here.

How do I add a while loop to an if/else statement

I am trying do add a while loop to this program. So far it generates 2 random numbers and the user must input the product of the numbers. Right now, the user has to re run the program each time. The goal is to have the user continue this until they decide to stop by entering the sentinel value: -1. Am I supposed to put the while loop right above the if statement?
Random random = new Random();
Scanner scan = new Scanner(System.in);
final int SENTINEL = -1;
int number1 = random.nextInt(13);
int number2 = random.nextInt(13);
int answer = number1 * number2;
System.out.print("What is " + number1 + " X " + number2 + "? > ");
int product = scan.nextInt();
if (product == answer) {
System.out.println("Correct! " + number1 + " X " + number2 + " = " + answer);
} else {
System.out.println("Wrong " + number1 + " X " + number2 + " = " + answer);
}
If you want the user to get a new randomly generated number each time, the while loop should go right before you generate the random numbers. In other words:
Random random = new Random();
Scanner scan = new Scanner(System.in);
final int SENTINEL = -1;
int number1;
int number2;
int product = 0;
while (product != SENTINEL) {
number1 = random.nextInt(13);
number2 = random.nextInt(13);
int answer = number1 * number2;
System.out.print("What is " + number1 + " X " + number2 + "? > ");
product = scan.nextInt();
if (product == answer) {
System.out.println("Correct! " + number1 + " X " + number2 + " = " + answer);
} else {
System.out.println("Wrong " + number1 + " X " + number2 + " = " + answer);
}
}
In general, the while statement should be placed before the first section of code you want to be repeated.
Something like this:
while(true){
number1 = random.nextInt(13);
number2 = random.nextInt(13);
int answer = number1 * number2;
System.out.print("What is " + number1 + " X " + number2 + "? > ");
int product = scan.nextInt();
if(product == SENTINEL){
System.exit(0); // you could also use break; here
}
if (product == answer) {
...
}

Simple Calculator Operation

I am attempting to simplify my long code of a calculator program, but I have a road block. I have a new else if statement for each calculator operator, but what I want to do is allow the user to manually type in, on one line, the entire operation they would like to perform and have the code compute it.
Here's what I have:
do {
System.out.println("What function would you like to perform?");
System.out.print("Exit Calculator (Q), Add (+), Subtract (-), Multiply (x), Divide (/): ");
maininput = in.next();
if (maininput.equals("+")) {
System.out.print("Enter the first number to add: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to add: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + answer);
System.out.println();
}
else if (maininput.equals("-")) {
System.out.print("Enter the first number to subtract: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to subtract: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("x")) {
System.out.print("Enter the first number to multiply: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to multiply: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 * num2;
System.out.println(num1 + " x " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("/")) {
System.out.print("Enter the first number to divide: ");
num1 = in.nextDouble();
do {
System.out.print("Enter the second number to divide: ");
num2 = in.nextDouble();
System.out.println();
if (num2 == 0) {
System.out.println("Cannot divide by 0! Please enter a different number.");
}
} while (num2 == 0);
answer = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("Q") || maininput.equals("q") || maininput.equals("EXIT") || maininput.equals("exit")) {
in.close();
System.exit(0);
}
else {
System.out.println(maininput + " is not a valid operand. Please try again.");
System.out.println();
}
} while (maininput != "Q" && maininput != "q");
This is what I want the output to be:
Enter operation:
4 * 6
4 * 6 = 24
Should be able to enter any operation here on one line. I am not asking you to write my calculator for me, I am asking how to allow the computer to read in the entire operation off one line and compute it, then print it.
If you use scanner readLine then you can read a whole line
e.g.
4 * 6
This line can then be split to get three tokens
String tokens [] = line.split (" ");
then you can see what operation to do based upon token[1]
if (token[1].equals ("-") {
//lets minus token[2] from token[0]
// need to convert String to Number
}
You can use String.split and store it in an array. Then it will return an array of string, parse those back to integers. the do the operation you want. The x variable will be the result.
if(maininput.contains("+")) {
String[] stringarr = string.split("\\+");
int x = Integer.parseInt(stringarr[0]) + Integer.parseInt(stringarr[1]);
System.out.println(stringarr[0] + " + " + stringarr[1] + " = " + x);
} else if(maininput.contains("-")) {
String[] stringarr = string.split("\\-");
int x = Integer.parseInt(stringarr[0]) - Integer.parseInt(stringarr[1]);
System.out.println(stringarr[0] + " - " + stringarr[1] + " = " x);
}
... And so on.
You could try parsing the line using a Pattern object, something like this:
Pattern opPattern = Pattern.compile("(\\d+) *([+-*/]) *(\\d+)");
Matcher matcher = opPattern.matcher(userLine);
if(matcher.find()) {
int op1 = Integer.toValue(matcher.group(1));
int op2 = Integer.toValue(matcher.group(3));
String op = matcher.group(2);
if(op.equals("+")) {
// do + op ...
} else ... {
// etc...
}
} else {
// error in line, not the form of an operation
}
Have a look at the javadoc, as I'm not sure if I used the correct method names and the like, just tried to illustrate the idea...

How to use the while loop and how to use the count in the loop

This program is designed to add 2 random numbers generated by the computer, when the user answer goes wrong , the computer tells the user to try it again, by using the while loop. The program will stop once the user enters a correct number. I have to calculate the wrong count in the while loop, however, it gives me the wrong count 1 when it is the second attempt.Please be kind enough to tell me where I go wrong in the code. Thank you.
import java.util.Scanner;
public class add {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = (int) (Math.random() * 10);
int num2 = (int) (Math.random() * 10);
int wrong = 0;
System.out.println("What is " + num1 + "+" + num2 + "=" + "?");
int answer = input.nextInt();
while (num1 + num2 != answer) {
System.out.println("Wrong answer, Try again . " +
"What is " + num1 + "+" + num2 + "? ");
answer = input.nextInt();
System.out.println("The number of attemt is " + wrong);
++wrong;
}
System.out.println("You got it correct !");
}
}
The error is in incrementing the number the user has gotten wrong AFTER printing "You got x wrong"
Just put ++wrong above System.out.println("The number of attemt is " + wrong);
while (num1 + num2 != answer) {
System.out.println("Wrong answer, Try again . " +
"What is " + num1 + "+" + num2 + "? ");
answer = input.nextInt();
++wrong;
System.out.println("The number of attemt is " + wrong);
}
Just change
wrong = 0
to
wrong = 1
wrong should probably be renamed to numberOfAttempts.
Initialize wrong to 1 instead of 0.
int wrong = 1;
A more appropriate name for the variable would be attempt if you take this approach.
You need to increment wrong before you display it:
import java.util.Scanner;
public class Add {
public static void main(String[] args ){
Scanner input = new Scanner (System.in);
int num1 = (int)(Math.random() * 10);
int num2 = (int)(Math.random() * 10);
int wrong = 0 ;
System.out.println("What is " + num1 + "+" + num2 + "=" + "?");
int answer = input.nextInt();
while (num1 + num2 != answer){
wrong++ ;
System.out.println("Wrong answer, Try again . What is " + num1 +"+"+ num2 + "? " );
answer = input.nextInt();
System.out.println("The number of attempt is " + wrong);
}
System.out.println("You got it correct !");
}
}

Categories