gpt4 book ai didi

android - 如何创建数字之间的操作?

转载 作者:行者123 更新时间:2023-11-29 00:54:37 29 4
gpt4 key购买 nike

首先我尝试在 kotlin 中创建操作代码,我的意思是当在终端中运行代码并输入第一个数字 123456 当我按下 + 运算符时代码读取它作为字符串选项,它将变为 123456+

底线是:我想创建运算符 kotlin 代码可以计算两个数字,当我按 +-/ or * 数字一的行必须干净才能输入数字二进行计算,因此输入数字三、四、五。

这是我的代码:

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)

}

最佳答案

今天早上我有时间。对于某些人来说,这可能是一个很好的问候世界,所以开始吧。

要读取输入并从中建立状态,您需要:

  • 从用户那里读取每个新参数的循环
  • 一种跟踪您已阅读输入的方法。这实际上是一个小状态机。我使用 enumwhen 表达式实现了我的。

这就是(可能不完全是您要查找的内容,但应该让您了解可能的结构:

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()
}
}
}
}
}

关于android - 如何创建数字之间的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55656863/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com