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)
}
答案 0 :(得分:2)
next()
返回一个String
,因此[]
运算符被转换为String
上的get
方法。索引为0时,此调用返回String
的第一个字符。
答案 1 :(得分:0)
如果reader.next()返回一个数组,则运算符将具有返回数组的第一个元素的值。