[SOLVED] can someone help how can i get random math operator ( kotlin)

Issue

This Content is from Stack Overflow. Question asked by Tom Levi

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)
        }



Solution

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]);


This Question was asked in StackOverflow by Tom Levi and Answered by Amir It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?