我想创建一个用户可以输入单词并输入字母的应用程序,应用程序将计算单词中使用该字母的次数。这是我的代码
public class LetterCount extends Activity {
Button CountLetter;
TextView Result;
EditText WordCount;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lettercounter);
Button CountLetter = (Button) findViewById(R.id.btncount);
CountLetter.setOnClickListener(new View.OnClickListener() {
//Declaring The Id in Xml
@Override
public void onClick(View v) {
TextView Result = (TextView) findViewById(R.id.numberletter);
EditText WordCount = (EditText) findViewById(R.id.txtletter);
String input = WordCount.getText().toString();
EditText Letter = (EditText) findViewById(R.id.txtletter);
Char lettercount = Letter.getText();
//loop for counting the letter in Word
int charCount = 0;
for(int i =0 ; i<input.length(); i++){
if(input.charAt(i) == lettercount){
charCount++;
}
}
//Displaying the result in Text View
Result.setText(charCount);
}
});
}
}
但单击按钮时应用程序停止工作。我该如何解决这个问题?
答案 0 :(得分:0)
您正在查找视图 txtletter 两次。相反,请使用另一个EditText,用户可以输入他们想要计算的字符,例如 letter
所以视图现在将是
EditText Letter = (EditText) findViewById(R.id.letter);
此外,如果要在textview中显示循环结果,请将其转换为字符串,而不是将int转换为字符串。
EditText Letter = (EditText) findViewById(R.id.letter); //user will enter which character they want to count
char lettercount = Letter.getText().toString().charAt(0); //read the character
//loop for counting the letter in Word
int charCount = 0;
for(int i =0 ; i<input.length(); i++){
if(input.charAt(i) == lettercount){
charCount++;
}
}
//Displaying the result in Text View
Result.setText(charCount + ""); //convert to string before passing to setText