以下代码的reader.next()[0]行中[0]的功能是什么

时间:2019-02-23 14:23:38

标签: kotlin java.util.scanner

import java.util.*

fun main(args: Array<String>) {
    val reader = Scanner(System.`in`)
    print("Enter two numbers: ")

    // nextDouble() reads the next double from the keyboard
    val first = reader.nextDouble()
    val second = reader.nextDouble()

    print("Enter an operator (+, -, *, /): ")
    val operator = reader.next()[0]

    val result: Double

    when (operator) {
        '+' -> result = first + second
        '-' -> result = first - second
        '*' -> result = first * second
        '/' -> result = first / second
        // operator doesn't match any case constant (+, -, *, /)
        else -> {
            System.out.printf("Error! operator is not correct")
            return
        }
    }

    System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result)
}

2 个答案:

答案 0 :(得分:2)

next()返回一个String,因此[]运算符被转换为String上的get方法。索引为0时,此调用返回String的第一个字符。

答案 1 :(得分:0)

如果reader.next()返回一个数组,则运算符将具有返回数组的第一个元素的值。