You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin开发Android字符串反转应用点击按钮闪退问题求助

崩溃原因定位

  1. 输入内容获取错误:直接调用EditText实例的toString()方法返回的是控件对象的类名+内存地址的描述字符串,并非用户输入的文本内容,会导致后续字符串分割、反转逻辑完全不符合预期。
  2. 数组下标越界:内层字符反转逻辑中,当左指针指向的字符属于排除字符时,代码错误执行了右指针自增操作,会让右指针持续超出字符数组的下标范围,直接触发ArrayIndexOutOfBoundsException崩溃。
  3. 输出逻辑异常:当前每处理完一个单词就直接给TextView赋值,最终只会显示最后一个单词的反转结果,无法输出完整的反转字符串。

修复后完整代码

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val button = findViewById<Button>(R.id.useButton)
        // 输入框、输出控件提前初始化,避免每次点击重复查找
        val userInputEt = findViewById<EditText>(R.id.userInput)
        val restrictedEt = findViewById<EditText>(R.id.restrictedChars)
        val outputTv = findViewById<TextView>(R.id.programOutput)

        button.setOnClickListener {
            // 正确获取输入文本
            val userInput = userInputEt.text.toString().trim()
            val exclusion = restrictedEt.text.toString().trim()
            // 输入为空直接返回避免崩溃
            if (userInput.isEmpty()) {
                outputTv.text = ""
                return@setOnClickListener
            }

            val wordsInString = userInput.split(" ")
            val resultBuilder = StringBuilder()

            wordsInString.forEach { currentWord ->
                val charArray = currentWord.toCharArray()
                var charPointerOne = 0
                var charPointerTwo = currentWord.length - 1

                while (charPointerOne < charPointerTwo) {
                    if (exclusion.contains(charArray[charPointerOne])) {
                        // 左指针指向排除字符,左指针右移
                        charPointerOne++
                    } else if (exclusion.contains(charArray[charPointerTwo])) {
                        // 右指针指向排除字符,右指针左移
                        charPointerTwo--
                    } else {
                        // 交换字符
                        val temp = charArray[charPointerOne]
                        charArray[charPointerOne] = charArray[charPointerTwo]
                        charArray[charPointerTwo] = temp
                        charPointerOne++
                        charPointerTwo--
                    }
                }
                // 拼接处理后的单词
                resultBuilder.append(String(charArray)).append(" ")
            }
            // 输出完整结果,去掉末尾多余空格
            outputTv.text = resultBuilder.toString().trimEnd()
        }
    }
}

内容的提问来源于stack exchange,提问作者j_md

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 15:30:00