import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.example.student.rexam.R.id.text
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
//etInput is an EditText element
//tvOutput is a TextView element
/**
* listener for a button in this activity
*/
fun filter(v: View) {
val input = etInput.text.toString()
val shortWords = shortWords(input)
val builder = StringBuilder()
for (word in shortWords) {
builder.append("$word, ")
}
val output = builder.toString()
tvOutput.setText("$output (${percentageShortWords()}%)")
}
val maxWordLength = 3
fun shortWords(text: String): List<String> {
var words = text.split(" ").toMutableList()
val iterator = words.iterator()
while (iterator.hasNext()) {
if (iterator.next().length > maxWordLength) {
iterator.remove()
}
}
return words
}
fun percentageShortWords(): Int {
val input = etInput.text.toString()
var words = input.split(" ").toMutableList()
val inputCount = words.count()
val outputCount = shortWords(input).count()
return ((outputCount.toDouble() / inputCount.toDouble()) * 100).toInt()
}
}
我如何将此代码重构为改进的形式? etInput是EditText元素,而tvOutput是TextView元素 一点点帮助将大有帮助 它的kotlin代码必须重构为替代或改进的形式。 编程新手,我真的需要