Kotlin开发Android字符串反转应用点击按钮闪退问题求助
崩溃原因定位
- 输入内容获取错误:直接调用
EditText实例的toString()方法返回的是控件对象的类名+内存地址的描述字符串,并非用户输入的文本内容,会导致后续字符串分割、反转逻辑完全不符合预期。 - 数组下标越界:内层字符反转逻辑中,当左指针指向的字符属于排除字符时,代码错误执行了右指针自增操作,会让右指针持续超出字符数组的下标范围,直接触发
ArrayIndexOutOfBoundsException崩溃。 - 输出逻辑异常:当前每处理完一个单词就直接给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
相关产品推荐
相关产品推荐

