Напиши калькулятор на Котлин для андроид студио
- User
Напиши калькулятор на Котлин для андроид студио
- Assistant
Напиши калькулятор на Котлин для андроид студио
Конечно! Давайте создадим простой калькулятор на языке Kotlin для Android Studio. Мы разработаем приложение, которое выполняет базовые арифметические операции: сложение, вычитание, умножение и деление.
CalculatorAPI 21: Android 5.0 (Lollipop)Откройте файл activity_main.xml, который находится в папке app/src/main/res/layout/, и замените его содержимое следующим кодом для создания интерфейса калькулятора:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Поле для вывода результата -->
<EditText
android:id="@+id/etInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="none"
android:enabled="false"
android:textSize="32sp"
android:gravity="end"
android:padding="16dp" />
<!-- Кнопки калькулятора -->
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:rowCount="5"
android:columnCount="4"
android:layout_marginTop="16dp">
<!-- Пример кнопок чисел и операций -->
<Button
android:id="@+id/btnClear"
android:layout_row="0"
android:layout_column="0"
android:layout_columnSpan="3"
android:text="C"
android:textSize="24sp"
android:layout_margin="4dp" />
<Button
android:id="@+id/btnDivide"
android:layout_row="0"
android:layout_column="3"
android:text="/"
android:textSize="24sp"
android:layout_margin="4dp" />
<Button
android:id="@+id/btn7"
android:layout_row="1"
android:layout_column="0"
android:text="7"
android:textSize="24sp"
android:layout_margin="4dp" />
<Button
android:id="@+id/btn8"
android:layout_row="1"
android:layout_column="1"
android:text="8"
android:textSize="24sp"
android:layout_margin="4dp" />
<Button
android:id="@+id/btn9"
android:layout_row="1"
android:layout_column="2"
android:text="9"
android:textSize="24sp"
android:layout_margin="4dp" />
<Button
android:id="@+id/btnMultiply"
android:layout_row="1"
android:layout_column="3"
android:text="*"
android:textSize="24sp"
android:layout_margin="4dp" />
<Button
android:id="@+id/btn4"
android:layout_row="2"
android:layout_column="0"
android:text="4"
android:textSize="24sp"
android:layout_margin="4dp" />
<Button
android:id="@+id/btn5"
android:layout_row="2"
android:layout_column="1"
android:text="5"
android:textSize="24sp"
android:layout_margin="4dp" />
<Button
android:id="@+id/btn6"
android:layout_row="2"
android:layout_column="2"
android:text="6"
android:textSize="24sp"
android:layout_margin="4dp" />
<Button
android:id="@+id/btnMinus"
android:layout_row="2"
android:layout_column="3"
android:text="-"
android:textSize="24sp"
android:layout_margin="4dp" />
<Button
android:id="@+id/btn1"
android:layout_row="3"
android:layout_column="0"
android:text="1"
android:textSize="24sp"
android:layout_margin="4dp" />
<Button
android:id="@+id/btn2"
android:layout_row="3"
android:layout_column="1"
android:text="2"
android:textSize="24sp"
android:layout_margin="4dp" />
<Button
android:id="@+id/btn3"
android:layout_row="3"
android:layout_column="2"
android:text="3"
android:textSize="24sp"
android:layout_margin="4dp" />
<Button
android:id="@+id/btnPlus"
android:layout_row="3"
android:layout_column="3"
android:text="+"
android:textSize="24sp"
android:layout_margin="4dp" />
<Button
android:id="@+id/btn0"
android:layout_row="4"
android:layout_column="0"
android:layout_columnSpan="2"
android:text="0"
android:textSize="24sp"
android:layout_margin="4dp" />
<Button
android:id="@+id/btnDot"
android:layout_row="4"
android:layout_column="2"
android:text="."
android:textSize="24sp"
android:layout_margin="4dp" />
<Button
android:id="@+id/btnEqual"
android:layout_row="4"
android:layout_column="3"
android:text="="
android:textSize="24sp"
android:layout_margin="4dp" />
</GridLayout>
</LinearLayout>
Пояснение:
etInput): Это поле для отображения ввода и результата. Оно отключено для редактирования пользователем, чтобы ввод осуществлялся только через кнопки.+, -, *, /), точки (.), очистки (C) и вычисления результата (=).MainActivity.ktОткройте файл MainActivity.kt и замените его содержимое следующим кодом:
package com.example.calculator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import java.lang.ArithmeticException
class MainActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var etInput: EditText
// Переменные для управления состоянием ввода
private var canAddOperation = false
private var canAddDecimal = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Убедитесь, что используете правильный layout
setContentView(R.layout.activity_main)
etInput = findViewById(R.id.etInput)
// Список всех кнопок
val buttons = listOf(
findViewById<Button>(R.id.btn0),
findViewById<Button>(R.id.btn1),
findViewById<Button>(R.id.btn2),
findViewById<Button>(R.id.btn3),
findViewById<Button>(R.id.btn4),
findViewById<Button>(R.id.btn5),
findViewById<Button>(R.id.btn6),
findViewById<Button>(R.id.btn7),
findViewById<Button>(R.id.btn8),
findViewById<Button>(R.id.btn9),
findViewById<Button>(R.id.btnPlus),
findViewById<Button>(R.id.btnMinus),
findViewById<Button>(R.id.btnMultiply),
findViewById<Button>(R.id.btnDivide),
findViewById<Button>(R.id.btnDot),
findViewById<Button>(R.id.btnClear),
findViewById<Button>(R.id.btnEqual)
)
// Назначение обработчика кликов для каждой кнопки
for (button in buttons) {
button.setOnClickListener(this)
}
}
override fun onClick(v: View?) {
if (v is Button) {
when (v.id) {
R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn3,
R.id.btn4, R.id.btn5, R.id.btn6, R.id.btn7,
R.id.btn8, R.id.btn9 -> {
etInput.append(v.text)
canAddOperation = true
}
R.id.btnPlus, R.id.btnMinus, R.id.btnMultiply, R.id.btnDivide -> {
if (canAddOperation && etInput.text.isNotEmpty()) {
etInput.append(v.text)
canAddOperation = false
canAddDecimal = true
}
}
R.id.btnDot -> {
if (canAddDecimal) {
etInput.append(v.text)
canAddDecimal = false
canAddOperation = false
}
}
R.id.btnClear -> {
etInput.text = ""
canAddOperation = false
canAddDecimal = true
}
R.id.btnEqual -> {
calculateResult()
}
}
}
}
private fun calculateResult() {
val expression = etInput.text.toString()
try {
val result = evaluate(expression)
etInput.setText(result.toString())
canAddOperation = false
canAddDecimal = true
} catch (e: ArithmeticException) {
Toast.makeText(this, "Ошибка", Toast.LENGTH_SHORT).show()
}
}
// Простая функция для вычисления выражения
private fun evaluate(expression: String): Double {
// Разделим строку на числа и операции
val tokens = mutableListOf<String>()
var currentNumber = ""
for (char in expression) {
if (char.isDigit() || char == '.') {
currentNumber += char
} else {
if (currentNumber.isNotEmpty()) {
tokens.add(currentNumber)
currentNumber = ""
}
tokens.add(char.toString())
}
}
if (currentNumber.isNotEmpty()) {
tokens.add(currentNumber)
}
// Первым шагом выполнить умножение и деление
var index = 0
while (index < tokens.size) {
if (tokens[index] == "*" || tokens[index] == "/") {
val left = tokens[index - 1].toDouble()
val right = tokens[index + 1].toDouble()
val oper = tokens[index]
val tempResult = if (oper == "*") {
left * right
} else {
if (right == 0.0) throw ArithmeticException("Деление на ноль")
left / right
}
// Заменяем три элемента на результат
tokens[index - 1] = tempResult.toString()
tokens.removeAt(index) // Удаляем оператор
tokens.removeAt(index) // Удаляем следующее число
index--
}
index++
}
// Затем выполнить сложение и вычитание
index = 0
while (index < tokens.size) {
if (tokens[index] == "+" || tokens[index] == "-") {
val left = tokens[index - 1].toDouble()
val right = tokens[index + 1].toDouble()
val oper = tokens[index]
val tempResult = if (oper == "+") {
left + right
} else {
left - right
}
// Заменяем три элемента на результат
tokens[index - 1] = tempResult.toString()
tokens.removeAt(index) // Удаляем оператор
tokens.removeAt(index) // Удаляем следующее число
index--
}
index++
}
if (tokens.size != 1) throw ArithmeticException("Неверное выражение")
return tokens[0].toDouble()
}
}
Инициализация компонентов:
findViewById и добавляем их в список buttons.setOnClickListener(this).Обработка нажатий кнопок в onClick:
etInput), после чего разрешается добавление операции.+, -, *, /): Добавляются только если предыдущий символ был цифрой или другим допустимым символом, чтобы избежать некорректных выражений..): Добавляется только один раз в одно число.C): Очищает поле ввода.=): Вызывает функцию calculateResult(), которая вычисляет выражение.Вычисление выражения в calculateResult():
evaluate.Функция evaluate(expression: String): Double:
Примечание: Для более сложных выражений и лучшей обработки ошибок рекомендуется использовать специализированные библиотеки для парсинга математических выражений, такие как Exp4j.
= и убедитесь, что результат отображается правильно.Обработка ошибок:
Поддержка скобок:
Расширенные функции:
Улучшение интерфейса:
Использование MVVM архитектуры:
Этот простой калькулятор поможет вам понять основы разработки Android-приложений на Kotlin. Вы можете дополнительно расширить функциональность и улучшить интерфейс по своему вкусу. Удачи в разработке!