【打造個人專屬計算機 APP】 系列文章目錄:
https://vocus.cc/article/65acea9ffd897800019c13dc
本課程學習如何實作處理加、減、乘和除按鈕等計算機相關邏輯。
若您無法順利觀看教學影片,請先登入您的 YouTube 帳號,然後點擊以下連結加入我們的頻道會員:
private var processText = ""
private var isFirstInput = true
private var isCalculated = false
onCreate
if (isCalculated && buttonText in "0".."9") {
processText = ""
processTextView.text = ""
resultTextView.text = ""
isFirstInput = true
isCalculated = false
}
when (buttonText) {
//計算機按鈕相關邏輯
}
"AC" -> {
processText = ""
processTextView.text = ""
resultTextView.text = ""
isFirstInput = true
isCalculated = false
}
"=" -> {
if (!isFirstInput) {
val result = evaluate(processText)
// 格式化結果以去除不必要的小數點
resultTextView.text = if (result.contains(".0")) {
result.dropLast(2)
} else {
result
}
isCalculated = true
}
}
"+/-" -> {
if (processText.isNotEmpty() && processText.toDoubleOrNull() != null && processText.toDouble() != 0.0) {
processText = if (processText.startsWith("-")) {
processText.drop(1)
} else {
"-$processText"
}
processTextView.text = processText
}
}
"⌫" -> {
if (processText.isNotEmpty()) {
processText = processText.dropLast(1)
processTextView.text = processText
}
}
"." -> {
if (!processText.endsWith(".") && !processText.contains(" .") && !processText.endsWith(
" "
)
) {
processText += if (isFirstInput || processText.last()
.isWhitespace()
) "0" else ""
processText += buttonText
processTextView.text = processText
isFirstInput = false
}
}
else -> {
if (buttonText in listOf("+", "-", "*", "/")) {
if (!isFirstInput && !processText.endsWith(" ")) {
processText += " $buttonText "
processTextView.text = processText
isFirstInput = true
}
} else {
processText += buttonText
processTextView.text = processText
isFirstInput = false
}
}
private fun evaluate(process: String): String {
return try {
val parts = process.split(" ")
var result = parts[0].toDouble()
var i = 1
while (i < parts.size) {
val operator = parts[i]
val nextNumber = parts[i + 1].toDouble()
when (operator) {
"+" -> result += nextNumber
"-" -> result -= nextNumber
"*" -> result *= nextNumber
"/" -> result /= nextNumber
}
i += 2
}
// 檢查結果是否為整數,並相應地格式化輸出
if (result % 1.0 == 0.0) {
result.toInt().toString()
} else {
result.toString()
}
} catch (e: Exception) {
"Error" // 錯誤時返回 "Error"
}
}