-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandomOperation.java
83 lines (66 loc) · 2.35 KB
/
RandomOperation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Random;
public class RandomOperation {
private Random magicNumber = new Random();
private BigDecimal firstTerm;
private BigDecimal secondTerm;
private BigDecimal result;
private int fractionDigits;
private char randomizedOperator;
public BigDecimal[] getOperation(int fractionDigit){
BigDecimal[] operation = new BigDecimal[2];
char[] operators = {'+','-','/','*'};
this.fractionDigits = fractionDigit;
operation[0] = this.round(this.random());
operation[1] = this.round(this.random());
this.firstTerm = operation[0];
this.secondTerm = operation[1];
this.randomizedOperator = operators[magicNumber.nextInt(4)];
return operation;
}
public BigDecimal random() {
BigDecimal max = new BigDecimal(99);
BigDecimal randFromDouble = new BigDecimal(Math.random());
BigDecimal actualRandomDec = randFromDouble.multiply(max);
actualRandomDec = actualRandomDec.setScale(2, BigDecimal.ROUND_DOWN);
return actualRandomDec;
}
public void setResult(int fractionDigits){
switch(randomizedOperator){
case '+':
result = firstTerm.add(secondTerm);
break;
case '-':
result = firstTerm.subtract(secondTerm);
break;
case '*':
result = firstTerm.multiply(secondTerm);
break;
case '/':
result = firstTerm.divide(secondTerm, this.fractionDigits);
break;
}
System.out.println(this.result);
this.result = this.round(this.result);
}
public char getOperatorSign(){
return this.randomizedOperator;
}
public BigDecimal round(BigDecimal userResult){
userResult = userResult.setScale(this.fractionDigits, RoundingMode.DOWN);
return userResult;
}
public BigDecimal toBigDecimal(String userInput){
BigDecimal userResult = new BigDecimal(userInput);
return this.round(userResult);
}
public boolean checkResult(String userResult){
if(this.result.equals(this.toBigDecimal(userResult))) {
return true;
}else{
return false;
}
}
}