В первом я попытался создать код операции в kotlin, я имею в виду, когда запускаю код в терминале и вводим первое число 123456
когда я 123456+
+
оператор, код считывает его как 123456+
опцию, и он становится 123456+
.
Суть в том, что я хочу создать код оператора, котлин может вычислить два числа, и когда я нажимаю +
или -
или /
или *
строка числа один должна быть чистой, чтобы ввести число два для вычисления и, таким образом, ввести число три и четыре. и пять
И это мой код:
fun operation(arr: ArrayList<String?>?) {
val joo = readLine()!!
val loo = joo.removeSuffix("+")
var soo = loo.toInt()
arr!!.add(soo.toString())
val voo = joo.lastIndex
when(voo.toString()){
"+" -> arr.last()!!.plus(soo)
}
println("${soo}")
operation(arr)
}
У меня есть время на руках сегодня утром. Это может быть хороший привет мир для кого-то, так что здесь.
Чтобы прочитать ввод и построить из него состояние, вам понадобится:
enum
и выражение when
.И вот оно (вероятно, не совсем то, что вы ищете, но должно дать вам представление о возможной структуре:
import java.util.*
// This gives us the states that our state machine can be in.
enum class State {
WANT_FIRST_OPERAND,
WANT_SECOND_OPERAND,
WANT_OPERATOR
}
fun main() {
val scanner = Scanner(System.'in')
var state = State.WANT_FIRST_OPERAND
println("Ready to do some maths!")
var firstOperand = 0.0
var secondOperand: Double
var operator = ""
// This loop will keep asking the user for input and progress through the states of the state machine.
loop@ while (true) {
// This when block encapsulates the logic for each state of our state machine.
when (state) {
State.WANT_FIRST_OPERAND -> {
println("Give me your first operand.")
try {
firstOperand = scanner.nextDouble()
state = State.WANT_OPERATOR
} catch (e: Exception) {
println("Sorry, that did not work, did you give me a number?")
scanner.nextLine()
}
}
State.WANT_OPERATOR -> {
println("Give me the operator. (+, -, /, *)")
try {
operator = scanner.next("[-*+/]+").trim()
state = State.WANT_SECOND_OPERAND
} catch (e: Exception) {
println("Sorry, that did not work.")
scanner.nextLine()
}
}
State.WANT_SECOND_OPERAND -> {
println("Give me your second operand.")
try {
secondOperand = scanner.nextDouble()
val answer = when(operator){
"+" -> firstOperand + secondOperand
"-" -> firstOperand - secondOperand
"/" -> firstOperand / secondOperand // You want to do something if second operand is 0 here
"*" -> firstOperand * secondOperand
else -> {
println("Hmmm, something went wrong there I don't know $operator, try again")
state = State.WANT_OPERATOR
continue@loop
}
}
println("The Answer is $answer, lets do another one!")
state = State.WANT_FIRST_OPERAND
} catch (e: Exception) {
println("Sorry, that did not work, did you give me a number?")
scanner.nextLine()
}
}
}
}
}
Enter
чтобы добавить клавишу оператора, это как раз моя проблема, я хочу отказаться от клавишиEnter
, значит, когда нажимаю какая-нибудь клавиша оператора+
или-
клавишаEnter
будет работать автоматически.