Java loop to ask 10 maths questions - java

Im currently trying to create a program thats asks the user to answer 10 multiplication questions and then output if the answer is correct or incorrect and then keep score of how many answers the user has got correct. My current code is shown below but I'm having trouble getting the score to increase as whenever I run it the score always stays at 1. I was wondering if anyone could help me with a solution to this
package Assignment1;
import java.util.Scanner;
import static java.lang.System.in;
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 11; i++) {
int number1 = (int) (Math.random() * 10) + 10;
int number2 = (int) (Math.random() * 10) + 10;
Scanner input = new Scanner(in);
System.out.print("What is " + number1 + " * " + number2 + " ?");
int answer = input.nextInt();
while ((number1 * number2) != answer) {
System.out.print("Incorrect");
answer = input.nextInt();
}
if ((number1 * number2) == answer) {
System.out.println("Correct");
int score = 0;
score = score + 1;
System.out.println("Score is currently: " + score);
}
}
}
}

In order to solve your problem, you need to understand the variable scope. The scope of a variable is in plain simple english: its lifecycle. And its lifecycle is defined between curly brackets, and by that I mean if the variable is created after "{", it only lives until "}". There are other cases, but don't mind them for now.
With this in mind, let's analyse what's the problem here. In your program you want the 'score' variable to live under all calculations and keep changing by adding the previous score to the new result, therefore producing a new score on every iteration. NOT to create a 'score' on every iteration.
Notice that you are creating the variable 'score' on every loop - resulting on its value being erased from memory (actually, its reference is what's being erased making its value lost in memory) at the end of every loop (when it dies) and a new 'score' variable is created over the next iteration.
So, I guess you'd know how to change your code now. You just change the creation of the variable 'score' to before the loop - so it's created before the "{" from the for loop instead of being erased and created on every iteration.
public class Main {
public static void main(String[] args) {
int score = 0;
for (int i = 0; i < 11; i++) {
int number1 = (int) (Math.random() * 10) + 10;
int number2 = (int) (Math.random() * 10) + 10;
Scanner input = new Scanner(in);
System.out.print("What is " + number1 + " * " + number2 + " ?");
int answer = input.nextInt();
while ((number1 * number2) != answer) {
System.out.print("Incorrect");
answer = input.nextInt();
}
if ((number1 * number2) == answer) {
System.out.println("Correct");
score = score + 1;
System.out.println("Score is currently: " + score);
}
}
}
}

You have declared score variable in the if block. So everytime there is a correct answer, the score is initialized with 0, then set to 1. Declare the score as an instance variable, or a local variable in main method (before the for loop)

If you want only 10 questions, the for loop should go from i = 1 to i < 11, not from i = 0. Also, you need to move the score outside the for loop, otherwise it will be declared as 0 every time the loop starts again. As Telmo Vaz correctly said, this is due to the scope of the variable. One other thing I noticed is that you can just use score++ to add 1 to score, instead of score = score + 1. I'll leave you to optimise your further.
import java.util.Scanner;
import static java.lang.System.in;
public class Main {
public static void main(String[] args) {
int score = 0;
for (int i = 1; i < 11; i++) { // 1 -> 10
int number1 = (int) (Math.random() * 10) + 10;
int number2 = (int) (Math.random() * 10) + 10;
Scanner input = new Scanner(in);
System.out.print("What is " + number1 + " * " + number2 + " ?");
int answer = input.nextInt();
while ((number1 * number2) != answer) {
System.out.print("Incorrect");
answer = input.nextInt();
}
if ((number1 * number2) == answer) {
System.out.println("Correct");
score++; // == (score = score + 1)
System.out.println("Score is currently: " + score);
}
}
}
}

Related

Using a return value from a method in another method

I'm trying to use the return value "average" in calcAverage method into the determineGrade method to get out a char value (A B C D F).
However, it repeats the loop when I code this way. Is there a way to just get the return value from the calcAverage and not have to execute the loop again and ask the same test scores?
package Chapter5;
import java.util.Scanner;
public class TestAverageAndGradewithLoop {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("How many tests?: ");
int test = input.nextInt();
System.out.print("Average test score is: " + calcAvergage(test) );
int mark = calcAvergage(test);
System.out.print("Letter grade is: " + determineGrade(mark) );
}
public static int calcAvergage(int test){
Scanner input = new Scanner (System.in);
int total = 0;
int x;
for (x = 1; x <= test; x++)
{
System.out.print("What is the score for test " + x + " : ");
int scores = input.nextInt();
total = total + scores;
}
int average = total/(x-1); //have to do -1 because the final increment value of x is stored as x+1
return average;
}
public static char determineGrade(int average)
{
char mark = 0;
if (average >= 90 && average <= 100)
{
mark = 'A';
}
else if (average >= 80 && average <= 89)
{
mark = 'B';
}
else if (average >= 70 && average <= 79)
{
mark = 'C';
}
else if (average >= 60 && average <= 69)
{
mark = 'D';
}
else if (average <= 60)
{
mark = 'F';
}
return mark;
}
}
Instead of this:
System.out.print("Average test score is: " + calcAvergage(test) );
int mark = calcAvergage(test);
Do this
int mark = calcAvergage(test);
System.out.print("Average test score is: " + mark );
There is no need to call the function twice when you are playing with the return value. Assign it to a variable and then use it.
Like this?
int mark = calcAvergage(test);
System.out.print("Average test score is: " + mark);
From my understanding you do not want to input a number then press enter then enter another number then press enter and so on...
If you say you have 3 test cases in console just type 3 space separated numbers like 10 12 3.
Your question is confusing and your code has logical errors, im sorry. You have if statements using the same logic.(example below) I would say learn up more on programming logic and you will answer your own question
else if (average >= 60 && average <= 69)
{
mark = 'D';
}
else if (average <= 60)
{
mark = 'F';
}
Thx to Avinash Raj for the pointer. I understand now.
the result of the calcAverage is stored in the variable mark, then I can use the int value from the result to both display what the score is as well as display and execute the determineGrade method.

How Do I Check If User Answer Is Same As Algebra Answer In Quiz?

I am making an algebra quiz in Java, and I want to check if the users answer is the same as the answer of the algebra equation. This is what i got already, the checking is towards the bottom. The first if statement is checking whether the 2nd number is positive or negative and calculates it. And the second if statement is trying to see whether the user answer is the same as the question answer. The problem is that Int answer cant be transferred over to the other if statement. Is there a way I can get around this? It is using an algebra equation like this: 1x + 2 = 5.
int numRight = 0;
Scanner input = new Scanner(System.in);
System.out.println("Welcome to your algebra test!");
System.out.println("What is your name?");
String name = input.nextLine();
System.out.println("Ok, " + name + ", how many questions do you want on your test?");
int numQuestions = input.nextInt();
for(int x = 0; x <= numQuestions; x++){
int coefficient = 7;
int num1 = 3;
int num2 = 23;
while((num2 - num1) % coefficient != 0){
coefficient = (int) (Math.random()*8)+2;
num1 = (int) (Math.random()*19)-9;
num2 = (int) (Math.random()*90)+10;
}
if(num1 > 0){
int part1pos = num2 - num1;
int answer = (coefficient / part1pos);
} else if(num1 < 0){
int part1neg = num1 + num2;
int answer = (coefficient / part1neg);
}
System.out.println(coefficient + "x + " + num1 + " = " + num2);
int userAnswer = input.nextInt();
if(userAnswer == answer){
System.out.println("The Answer is correct!");
numRight++;
} else{
System.out.println("The answer is wrong!");
}
}
The problem is that your answer integer is declared within a different scope from your boolean statements that check for answer correctness. You should declare and initialize your answer as 0 outside of that boolean statement, around where you declare your coefficient, num1, and num2.

How to calculate circumference with random numbers?

I need to print the circumference with Math.random() * Math.Pi; but i'm doing something wrong or missing something. Each random generated number equals the radius of the circle. My idea was to calculate Pi in the getRandomNumberInRange method but when I do, I get error:
Bad operand for type double
import java.util.Random;
import java.util.Scanner;
final static double PI = 3.141592564;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
//ask the player to enter a number less than or equal to 18 and higher to 9.
System.out.println(" Please enter a number less than or equal to 18 and above 9: ");
int random = sc.nextInt ();
//send error message if bad input
if (random < 9 || random > 18) {
System.out.println(" Error. Unauthorized entry . You need to enter a number less than or equal to 18 and above 9 ");
} else
//If the answer is yes , generate nine different random numbers from 0.
for (int i = 0; i < 9; i++) {
double surface = PI * (random * 2);
System.out.println(getRandomNumberInRange(9, 18) + " : " + " The circumference is : " + surface );
}}
The method called:
private static int getRandomNumberInRange(int min, int max) {
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
You call getRandomNumberInRange() in the for loop, but don't assign it to anything, or use it.
This is probably closer to what you want:
for (int i = 0; i < 9; i++) {
int r2 = getRandomNumberInRange(9, 18);
double surface = PI * (r2 * 2);
System.out.println(r2 + " : " + " The circumference is : " + surface);
}

Java: Min/Max/Average (4 variables) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Anyone knows how to run this program using 4 variables only? I tried using 1 variable for min and max "lowhigh" but I was having a hard time figuring out where to put the statements.
int numbers[] = new int[5];
int low = 0; int high = 0;
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
if (count == 0) {
low = number;
high=number;
} else {
if(number < high) {
high= number;
}
if(number > low){
low = number;
}
}
numbers[count] = number;
}
double ave = numbers[0]+numbers[1]+numbers[2]+numbers[3]+numbers[4]/5;
System.out.println("Highest: " +high);
System.out.println("Lowest: " +low);
System.out.println("The average of all number is: " +ave); }}
Another way to do it in Java 8.
int numbers[] = new int[5];
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
numbers[count] = number;
}
LongSummaryStatistics statistics = Arrays.stream(numbers)
.asLongStream()
.summaryStatistics();
System.out.println("Highest: " + statistics.getMax());
System.out.println("Lowest: " + statistics.getMin());
System.out.println("The average of all number is: " + statistics.getAverage());
Looks like your logic is backwards to finding high and low. Also your average wont work because order of operations. Need parens
int numbers[] = new int[5];
int low = Integer.MAX_VALUE; int high = Integer.MIN_VALUE;
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
if (count == 0) {
low = number;
high=number;
} else {
if(number > high) {
high= number;
}
if(number < low){
low = number;
}
}
numbers[count] = number;
}
double ave = (numbers[0]+numbers[1]+numbers[2]+numbers[3]+numbers[4])/5;
System.out.println("Highest: " +high);
System.out.println("Lowest: " +low);
System.out.println("The average of all number is: " +ave); }}
You don't have to use an array if all you're doing is finding the min, max and mean.
final int COUNT = 5; //this is just to be neat, and not needed as a variable.
int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;
int sum = 0;
for(int i = 0; i < COUNT; i++){
int n = s.nextInt();//or whatever
if(n > high)
high = n;
if(n < low)
low = n;
sum += n;
}
System.out.println("Max: " + high);
System.out.println("Min: " + low);
System.out.println("Average: " + ((double) sum) / COUNT);
Based on what you mean by 4 variables, this may or may not work. final int COUNT is not really required and 5 can be put in directly instead.
This answer likely goes well beyond the scope of the question, but since the requirements/restrictions are not listed in full, it may still be a valid answer.
With a super strict interpretation of "4 variables", even the Scanner variable s counts.
Using streams, it can be done with 3 variables:
Scanner s; // variable 1
List<Double> values; // variable 2
String line; // variable 3
s = new Scanner(System.in);
values = new ArrayList<>();
while (true) {
System.out.print("Please enter a numbers, or press enter when done: ");
if ((line = s.nextLine().trim()).isEmpty())
break;
values.add(Double.valueOf(line));
}
if (values.isEmpty())
return;
System.out.println("Minimum: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.min().getAsDouble());
System.out.println("Maximum: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.max().getAsDouble());
System.out.println("Average: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.sum() / values.size());
Sample output
Please enter a numbers, or press enter when done: 10
Please enter a numbers, or press enter when done: 42
Please enter a numbers, or press enter when done: 19
Please enter a numbers, or press enter when done: 88
Please enter a numbers, or press enter when done: 1
Please enter a numbers, or press enter when done: 3774
Please enter a numbers, or press enter when done:
Minimum: 1.0
Maximum: 3774.0
Average: 655.6666666666666
There is no point in the numbers[] array; so eliminate that.
You need a control variable for the loop, a temporary storage for the input, then three running variables for min, max and sum (average is sum devided by count, which seems to be fixed to 5).
Thats 5 variables, and you strictly need all of them. Its possible to stuff multiple values into a single variable, but I highly doubt thats what you're supposed to do.
Depending on what the requirements really are (I presume this is homework), one of the five I named above doesn't count as a variable per requirement (most likely the loop control or the temporary input storage).
Edit: Here's a variant using multiple values encoded in one variable that works with three variables (or four if you count the scanner, which I replaced with random for my convinience):
public class HighLowAverage {
public static void main(String[] args) {
long sum = 0;
long highLow = 0x8000_0000_7FFF_FFFFL;
long countNumber = 0;
for (; (countNumber >> 32) < 5; countNumber += 0x1_0000_0000L) {
countNumber = (countNumber & 0xFFFF_FFFF_0000_0000L)
| ((int) (Math.random() * 100) & 0xFFFF_FFFFL);
System.out.println(((countNumber >> 32) + 1) + ". number is: " + (int) countNumber);
sum += (int) countNumber;
if ((highLow >> 32) < (int) countNumber)
highLow = (highLow & 0xFFFF_FFFFL) | (countNumber << 32);
if (((int) highLow) > (int) countNumber)
highLow = (highLow & 0xFFFF_FFFF_0000_0000L) | (countNumber & 0xFFFF_FFFFL);
}
System.out.println("Average: " + ((double) sum) / (countNumber >> 32));
System.out.println("Min: " + (int) highLow);
System.out.println("Max: " + (highLow >> 32));
}
}
The techniques used are bit-shifting and masking to use the upper/lower half of the long datatype as independendly accessible values. Note amount of complicated expressions necessary as well as the numerous constansts in the expressions plus typecasts almost everywhere.
This is code you should never ever use - it works, but even an experienced programmer will need an excessive amount of thinking to figure out if its working correctly. My guess is that a typical beginner class teacher will have trouble understanding it at all.
Edit2: Scratch the above, it can be done with one variable. How? By replacing multiple variables with an array:
public static void main(String[] args) {
long[] vars = new long[5];
vars[1] = Long.MIN_VALUE;
vars[2] = Long.MAX_VALUE;
for (vars[0] = 0; vars[0] < 5; ++vars[0]) {
vars[4] = (int) (Math.random() * 100);
System.out.println((vars[0] + 1) + ". number is: " + vars[4]);
vars[3] += vars[4];
if (vars[4] > vars[1])
vars[1] = vars[4];
if (vars[4] < vars[2])
vars[2] = vars[4];
}
System.out.println("Average: " + ((double) vars[3]) / vars[0]);
System.out.println("Min: " + vars[1]);
System.out.println("Max: " + vars[2]);
}
Needless to say thats still confusing code. Each index of the vars array is used to hold one of the variables (0 = loop control, 1 = min, 2 = max, 3 = sum, 4 = number).
You see it all depends on what is considered a variable.

Is it possible to increase array index in a loop?

So my problem is that if you want to get a new calculation, the operaotr in my array should change. How can i do that? im trying this now for hours :/ this is how far i got.
so first it starts with + and whan you choose to get a new calculation the next one should be - and so on....
so i need to switch the "operator[0]"
private static void mathGame() {
char[] operator = {'+', '-', '*', '/'};
int x;
int y = 0;
Scanner input = new Scanner(System.in);
do {
int operand1 = (int) (Math.random() * (100 - 1) + 1);
int operand2 = (int) (Math.random() * (100 - 1) + 1);
System.out.println("Solve");
System.out.println(operand1 + " " + operator[0] + " " + operand2);
x = input.nextInt();
// operator [1]++;
if (x == evaluate(operand1, operator[0], operand2)) {
System.out.println("True!");
System.out.println("New Challange?");
y = input.nextInt();
//operator[1]++;
} else if (x != evaluate(operand1, operator[0], operand2)) {
System.out.println("False!");
System.out.println("New Challange?");
y = input.nextInt();
//operator[1]++;
}
} while (y == 1);
}
You need to define a variable outside of your loop (int i = 0;) and then have this instruction inside the loop (maybe before "} while (y == 1);":
i = (i + 1) % 4; (4 is size of your operators array).
p.s. I think you need to give more details about your question and elaborate your question in order to make it more clear for future readers.

Categories

Resources