Android x Kotlin 實作課程:打造個人專屬計算機 APP EP6 計算機邏輯

HKT實驗室
發佈於Android 入門指南 個房間
2024/02/01閱讀時間約 8 分鐘

打造個人專屬計算機 APP 系列文章目錄:
https://vocus.cc/article/65acea9ffd897800019c13dc

課程摘要

本課程學習如何實作處理加、減、乘和除按鈕等計算機相關邏輯。

教學影片

若您無法順利觀看教學影片,請先登入您的 YouTube 帳號,然後點擊以下連結加入我們的頻道會員:

  • 一般會員:成為一般會員後,您將能夠觀看我們所提供的一般會員專屬線上課程。
  • 精實會員:成為精實會員後,您將能夠觀看我們所提供的精實會員專屬線上課程。

範例程式碼

MainActivity.kt

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 按鈕邏輯

"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
}
}

Backspace 按鈕邏輯

"⌫" -> {
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 不是以上相關按鈕邏輯

else -> {
if (buttonText in listOf("+", "-", "*", "/")) {
if (!isFirstInput && !processText.endsWith(" ")) {
processText += " $buttonText "
processTextView.text = processText
isFirstInput = true
}
} else {
processText += buttonText
processTextView.text = processText
isFirstInput = false
}
}

evaluate 函數

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"
}
}
3會員
176內容數
本指南將以清晰易懂的方式介紹基礎概念,讓你能夠快速上手,輕鬆踏上學習 Kotlin 的旅程 透過簡單易懂的方式,讓你將能夠在短時間內建立起對 Kotlin 的基本了解,並開始實際應用於你的專案之中。不論你是想要進入 Android 開發領域或者只是想探索新的程式語言,這份指南都會成為你學習 Kotlin 的理想起點。
留言0
查看全部
發表第一個留言支持創作者!