0

I wanted to use && with while loop in Kotlin but it's not working. First, I generated 2 random numbers, then checked if they are more than 5 and if isn't generate new numbers until they're more than 5.

fun main(args : Array<String>){

    val rand = Random()
    var a:Int = rand.nextInt(10)
    var b:Int = rand.nextInt(10)
    
    while (a<5 && b<5){
        a = rand.nextInt(10)
        b = rand.nextInt(10)
    }
    
    println("a is "+a)
    println("b is "+b)
}

output is:

a is 1
b is 6
11
  • 4
    You want OR, not AND. Commented Jul 18, 2020 at 16:46
  • 1
    I want both numbers to be more than 5 Commented Jul 18, 2020 at 16:48
  • 3
    you need to use logical OR for this a<5 || b<5, same with &&: !(a >= 5 && b >= 5) Commented Jul 18, 2020 at 16:51
  • 2
    The condition with AND is to keep looping while both values are below five. As soon as one of the values becomes greater than five the condition is no longer true. Commented Jul 18, 2020 at 16:57
  • 1
    @IR42 is correct: you want a >= 5 && b >= 5. So you want to keep generating numbers when that is NOT the case. The boolean inverse of this expression is a<5 || b<5. In other words, if either one of those numbers is lower than 5, you want to keep generating numbers. Commented Jul 18, 2020 at 16:57

1 Answer 1

1

You are using incorrect logical condition. If you want both numbers to be more than 5 use condition a<5 || b<5 in the while loop:

val rand = Random()
var a:Int = rand.nextInt(10)
var b:Int = rand.nextInt(10)

while (a < 5 || b < 5) {
    a = rand.nextInt(10)
    b = rand.nextInt(10)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.