I am coding a problem where it will be x (+ or - or *) y =z and it will generate 4 possible answers for the user which has 1 good and 3 wrong answers. I made most of the code but I do not get how I make the same formula used again for Reponse() because right now when I execute the code, Equation() makes his own one and Reponse() does another different formula. Also I need to know how I can make sure that the code works by adding a system that will show a formula like 5 +5 = ? and the code will show 4 answers which has one good one.
here's the code:
public class Equation {
int x, y, z;
public Equation() {
Random r = new Random();
x = r.nextInt(50) + 1;
y = r.nextInt(50) + 1;
z = 0;
char operator = '?';
switch (r.nextInt(3)) {
case 0:
operator = '+';
z = x + y;
break;
case 1:
operator = '-';
z = x - y;
;
break;
case 2:
operator = '*';
z = x * y;
;
break;
default:
operator = '?';
}
System.out.print(x);
System.out.print(" ");
System.out.print(operator);
System.out.print(" ");
System.out.print(y);
System.out.print(" = ");
System.out.println(z);
}
}
and for Reponse() the one that generates the answers:
public class Reponse {
Equation equ = new Equation();
int a, b, c, d;
char operator = '?';
public Reponse() {
Random r = new Random();
switch (r.nextInt(4)) {
case 0:
a = r.nextInt(2 * equ.z);
break;
case 1:
b = r.nextInt(2 * equ.z);
break;
case 2:
c = r.nextInt(2 * equ.z);
break;
case 3:
d = equ.z;
break;
default:
operator = '?';
}
}
}
This is because you are initializing the new instance of Equation
class inside your Response
class.
Equation equ = new Equation();
Whenever you'll do something like,
Response r = new Response();
A new instance of Equation
will be instantiated.
What you should be doing is as follows,
Change the Response
class as follows:
public class Response { int a, b, c, d; char operator = '?'; public Response(Equation equ) { Random r = new Random(); switch (r.nextInt(4)) { case 0: a = r.nextInt(2 * equ.z); break; case 1: b = r.nextInt(2 * equ.z); break; case 2: c = r.nextInt(2 * equ.z); break; case 3: d = equ.z; break; default: operator = '?'; } } }
Note: I have deleted the instance of Equation
from the class and am passing it to the constructor.
Create a new instance of Equation
,
Equation equ = new Equation();
Create a new instance of Response
by passing above Equation
instance,
Response r = new Response(equ);
Now, you can create multiple instances of Response
class using the same instance of the Equation
class that you instantiated.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.