Home > Blockchain >  How to find the largest number of a sequence?
How to find the largest number of a sequence?

Time:10-31

I am trying to solve a problem where i need to input numbers in a while loop. The loop will stop if user input the number 0. Then the code should give an output of the biggest number.

import java.util.*
fun main() {
    val scanner = Scanner(System.`in`)
    var remainder = 0
    val n = scanner.nextInt()
    while (n != 0) {
        var input = scanner.hasNextInt()
        if (input > remainder) {
            remainder = input
        }
    }
    println(remainder)
}

But when i try to run the code i get this error message:

Compilation error
main.kt:8:21: error: type mismatch: inferred type is Int but Boolean was expected
        if (input > remainder) {
                    ^
main.kt:9:25: error: type mismatch: inferred type is Boolean but Int was expected
            remainder = input
                        ^

CodePudding user response:

You're getting an error because this method scanner.hasNextInt() returns a boolean value and you're comparing the boolean value with an integer value.

import java.util.*
fun main() {
    val scanner = Scanner(System.`in`)
    var remainder = 0
    val n = scanner.nextInt()
    while (n != 0) {
        var input = scanner.nextInt()
        if (input > remainder) {
            remainder = input
        }
    }
    println(remainder)
}

You should use scanner.nextInt() if you're not getting any string or other kind of input. If you're getting any other kind of input you can use scanner.hasNextInt() and then take the input.

CodePudding user response:

You can also use Kotlin's readLine() function to take user input. The code will be like this:

var answer = 0
while(true) {
    val n = readLine()!!.toInt()
    if(n == 0) break
    answer = maxOf(answer, n)
}
println(answer)
  • Related