Reputation: 2865
So i have an EditText in my app where the user types in an aswer. My problem is that when i check the input and use a conditional to check if it is the correct answer it gets overcomplicated. Here's my code so you get a better understanding of my question
if (cuenta == 0) {
if (inputbox.getText().toString().equals("Ottawa")) {
resultadolabel.setText("Correcto");}
else if (inputbox.getText().toString().equals("Ottawa ")) {
resultadolabel.setText("Correcto");}
else if (inputbox.getText().toString().equals("ottawa")) {
resultadolabel.setText("Correcto");}
else if (inputbox.getText().toString().equals("ottawa ")) {
resultadolabel.setText("Correcto");}
else {resultadolabel.setText("Respuesta correcta: Ottawa");}
}
As you can see i ask for the capital of Canada, but i want the user to be able to write the text in 4 different ways (Capital letter w/space at the end, lower case leer w/no space at the end, etc..). This where my question comes up, is there a way to make some sort of "if (this condition, or this other condition or this other condition etc..)
I really need a way to simplify my code because it will get REALLY long specially with countries with accent and stuff.
Upvotes: 1
Views: 130
Reputation: 6557
Use regex:
if(inputbox.getText().toString().matches("^[oO]ttawa\\s?")){
resultadolabel.setText("Correcto");
} else{
resultadolabel.setText("Respuesta correcta: Ottawa");
}
Upvotes: 0
Reputation: 2440
Try condition with trim()
which Returns a copy of the string, with leading and trailing whitespace omitted. and use equalsIgnoreCase()
which ignoring case considerations.
if (inputbox.getText().toString().trim().equalsIgnoreCase("ottawa")) {
resultadolabel.setText("Correcto");
} else {resultadolabel.setText("Respuesta correcta: Ottawa");}
Upvotes: 0
Reputation: 36304
public static void main(String[] args) {
String s="Ottawa ";
s=s.trim();
if(s.equalsIgnoreCase("ottawa"))
{
resultadolabel.setText("Correcto");
}
else {resultadolabel.setText("Respuesta correcta: Ottawa");}
}
Upvotes: 0
Reputation: 107387
Here's what I would do:
if (inputbox.getText().trim().toUpperCase().equals("OTTAWA")) { ...
This would obviously also allow permutations such as " OtTaWa" and "ottawA", but you really can't afford to check all permutations one by one. Possibly introduce a rule that the first letter must be capitalized?
Note that you don't need to toString()
the return of getText()
- it is already a String.
Upvotes: 0
Reputation: 43023
You can just use toLowerCase()
and trim()
if (inputbox.getText().toString().toLowerCase().trim().equals("ottawa"))
Upvotes: 0
Reputation: 5102
you can use equalsIgnoreCase()
and trim()
, for example:
if(inputbox.getText().toString().trim().equalsIgnoreCase("Ottawa")){
resultadolabel.setText("Correcto");
}
Upvotes: 3