hello guys am new to kotlin i try to make a quiz app , so the questions that included strings i put them manually and math questions are random ( loop ) the help i ask for how can i get random math operator here
println("${randomNumber1} * ${randomNumber2}")
also println("${randomNumber1} * ${randomNumber2}")
part from the code :
try {
for (i in defaultMain until defaultMain 40) {
val randomNumber1 = (0..30).random()
val randomNumber2 = (1..10).random()
println("${randomNumber1} * ${randomNumber2}")
var input = readLine()!!.toInt()
when (input) {
randomNumber1 * randomNumber2 -> "Right! 5 Points added to your score , and 5 bonus"
else -> lose() }
this.bonus = this.bonus 5
this.score = this.score 5
this.score = this.score this.bonus
println("Your current score: ${this.score}")
}
} catch (e : Exception)
{
println(e.message)
exitProcess(0)
}
CodePudding user response:
define operators in an array like below and access from index by generating random number:
char[] x = { '-', ' ', '*', '/', '^', '%' };
Random random = new Random();
int random_operator = random.nextInt(x.length);
System.out.println(x[random_operator]);
CodePudding user response:
Maybe something like this?
val randomNumber1 = (0..30).random()
val randomNumber2 = (1..10).random()
val operator = (1..4).random()
val solution = when (operator) {
1 -> {
println("$randomNumber1 * $randomNumber2")
randomNumber1 * randomNumber2
}
2 -> {
println("$randomNumber1 / $randomNumber2")
randomNumber1 / randomNumber2
}
3 -> {
println("$randomNumber1 - $randomNumber2")
randomNumber1 - randomNumber2
}
else -> {
println("$randomNumber1 $randomNumber2")
randomNumber1 randomNumber2
}
}
var input = readLine()!!.toInt()
if (input == solution)
println("Right! 5 Points added to your score , and 5 bonus")
else
lose()