I have an assignment in my programming class. It goes like this, I have to make a program which takes the input of the user how many exercises he wants to do. Then he solves simple calculations with random numbers from 1-10 and with random operators. In the end, it should write how many correct and incorrect ones did he get. It also should write the elapsed time of the task. I did some work, but when I assign a random value to an operation
int operation = (int)(Math.random()*3)+1;
or to a number a and b
int a = (int)(Math.random()*10); int b = (int)(Math.random()*10);
I always get the same number and operator when I choose for the second or third time my task (because I use a loop). Is there a way to change the same initialized variable or operator during a program. For example that int a=(int)(Math.Random()*10)
is initialized in the beginning as for example as 3, and later when the program loops again to initialize it as a different number, for example 6. Are there any others solutions for my problem? Here is my whole code, for now:
import java.util.*;
import javax.swing.JOptionPane;
public class RandomChar {
public static void main(String[] args) {
char op= ' ';
int operation = (int)(Math.random()*3)+1;
int a = (int)(Math.random()*10);
int b = (int)(Math.random()*10);
String s;
int correct = 0, incorrect=0;
s = JOptionPane.showInputDialog("How many exercises do you want?");
int num = Integer.parseInt(s);
long tStart = System.currentTimeMillis();
while(num>0){
if(operation==1)
op='+';
else if(operation==2)
op='-';
else if(operation==3)
op='*';
String str1 = JOptionPane.showInputDialog(a+" "+op+" "+b+" = ");
int num1 = Integer.parseInt(str1);
if(op=='+'){
if(a+b==num1)
correct++;
else
incorrect++;
}else if(op=='-'){
if(a-b==num1)
correct++;
else
incorrect++;
}else if(op=='*'){
if(a*b==num1)
correct++;
else
incorrect++;
}
num--;
}
long tEnd = System.currentTimeMillis();
long tOverral = tEnd - tStart;
double elapsedSeconds = tOverral / 1000.0;
System.out.println("Correct: "+correct);
System.out.println("Incorrect: "+incorrect);
System.out.println("Elapsed seconds: "+ elapsedSeconds);
}
}
Aucun commentaire:
Enregistrer un commentaire