【打造個人專屬計算機 APP】 系列文章目錄:
https://vocus.cc/article/65acea9ffd897800019c13dc
本課程學習如何透過函數重構程式碼,提高可讀性、可維護性和重用性。以按鈕操作為例,將不同邏輯提取成函數,例如 allClear()、equalSign() 等,使程式碼更簡潔易懂,提升開發效率。
若您無法順利觀看教學影片,請先登入您的 YouTube 帳號,然後點擊以下連結加入我們的頻道會員:
when (buttonText) {
"AC" -> allClear()
"=" -> equalSign()
"+/-" ->toggleSign()
"⌫" -> backspace()
"." -> dotSign(buttonText)
else -> {
handleNumberOrOperator(buttonText)
}
}
private fun handleNumberOrOperator(buttonText: String) {
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 dotSign(buttonText: String) {
if (!processText.endsWith(".") &&
!processText.contains(" .") &&
!processText.endsWith(
" "
)
) {
processText += if (isFirstInput || processText.last()
.isWhitespace()
) "0" else ""
processText += buttonText
processTextView.text = processText
isFirstInput = false
}
}
private fun backspace() {
if (processText.isNotEmpty()) {
processText = processText.dropLast(1)
processTextView.text = processText
}
}
private fun toggleSign() {
if (processText.isNotEmpty() &&
processText.toDoubleOrNull() != null &&
processText.toDouble() != 0.0
) {
processText = if (processText.startsWith("-")) {
processText.drop(1)
} else {
"-$processText"
}
processTextView.text = processText
}
}
private fun equalSign() {
if (!isFirstInput) {
val result = evaluate(processText)
resultTextView.text = if (result.contains(".0")) {
result.dropLast(2)
} else {
result
}
isCalculated = true
}
}
private fun allClear() {
processText = ""
processTextView.text = ""
resultTextView.text = ""
isFirstInput = true
isCalculated = false
}