android - 如何创建数字之间的操作?
问题描述
在第一次我尝试在 kotlin 中创建操作代码时,我的意思是当我在终端中运行代码并输入第一个数字123456
时,当我按下+
操作符时,代码将其读取为字符串选项,它将变为123456+
.
底线是:我想创建可以计算两个数字的运算符 kotlin 代码,当我按+
或-
或或/
或数字时*
,数字一的行必须干净才能输入数字二进行计算,因此输入数字三、四和五。
这是我的代码:
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()
}
}
}
}
}
推荐阅读
- vb.net - VB.NET 连接字符串与门禁控制器CHIYU BF Mini -WE
- java - 将 FileOutputStream 与 CSVWriter 一起使用的声纳主要警报
- html - 无法使按钮在css中看起来很平滑
- opengl - 使用 FFmpeg -> QSV -> glTexImage2D 将视频帧解码为 OpenGL 纹理
- android - 如何阻止基于 SharedPreferences 值的通知?
- python - sqlalchemy 两次声明相同的模型
- python - 延长最短生产时间要求的问题
- ruby-on-rails - 损坏的模拟中的 RSpec NoMethodError
- tensorflow - Tensorflow 中 LSTM 的 One-Hot Encoding (OHE) 巨大语料库
- javascript - Chrome 开发工具:在性能分析工具中查找事件的来源?