EditText equals
I have a search app that only has 150 files. So if somebody searches for 151, it would say "the file 151 can't be found".
I have the code:
EditText edit = (EditText) findViewById(R.id.editText1);
if (edit.getText().toString().equals("151")) {
edit.setError("Invalid File Name");
} e开发者_如何学运维lse {
// Do nothing;
}
But I have 2 questions:
- How can I set
.equals("151")
to something like:.equals("151" >)
(151 and up)? - What is the code of: "Do nothing"?
You create an int from the string. Like this:
int aInt = Integer.parseInt(edit.getText().toString()); if(aInt > 150) dostuff();
To do nothing, just add ";".
if(foo) dostuff(); else ;
You need to parse the EditText
's value to an Integer, so you can compare it using the operators. Like so:
if (Integer.valueOf(edit.getText().toString()) > 150 ) {do stuff;})
You probably want to first parse it (inside a try catch block), then do if/else depending on whether or not the value is within range. For showing a quick validation message to the user you probably want to use a Toast notification.
You can make it that way
int num = Integer.parse(edit.getText().toString());
if(num >= 151) {
} else {
}
You need to parse it as an integer and you also need to handle the case where the string cannot be parsed as an integer. You MUST be prepared to catch the NumberFormatException if the value is coming from user input!
try{
int i = Integer.parseInt(edit.getText().toString());
if(i>150){
// Do stuff if i > 150
}
else{
// Stuff if i < 151
}
}catch(NumberFormatException e){
// Deal with the fact that the file name is not a valid integer number (e.g. "ABC")
}
精彩评论