Which one of these would be the best way to do this when you have very long IfElse?
if (text.contains("text"))
{
// do the thing
}
else if (text.contains("foo"))
{
// do the thing
}
else if (text.contains("bar"))
{
// do the thing
}else ...
Or
if (text.contains("text") || text.contains("foo") || ...)
{
// do the thing
}
Or maybe
Pattern pattern = Pattern.compile("(text)|(foo)|(bar)|...");
Matcher matcher = pattern.matcher(text);
if(matcher.find())
{
// do the thing
}
And I mean ONLY when you have to check a lot of these. Thanks!
I would personally use a set as I think it is easier to read and the contains will be efficient in O(1):
Set<String> keywords = new HashSet<String>();
keywords.add("text");
keywords.add("foo");
keywords.add("bar");
if(keywords.contains(text)) {
//do your thing
}
And if you like it compact, you can also write:
Set<String> keywords = new HashSet<String>(Arrays.asList("text", "foo", "bar"));
if(keywords.contains(text)) {
//do your thing
}
And finally, if you always use the same list, you can make keywords private static final instead of recreating it each time you run the method.
EDIT
Following a comment, it is true that what is above is equivalent to using a condition with text.equals("xxx"), not text.contains("xxx"). If you really meant to use contains, then you would have to iterate over the set and test each string, but it becomes an O(n) operation:
for (String key : keywords) {
if (text.contains(key)) {
//do your stuff
break;
}
}
Usually long If else statements are replaced with case statements, but this is not always possible. If I where to recommend, I would go for the second option, option 1 will give you a bunch of If else if else statements which do the same thing while for the third case, regular expressions tend to grow pretty large pretty fast.
Again depending on how much alot is, it could eventually be better to just throw all your strings in a data structure and iterate over it to see if the element is in it.
String[] storage = {
"text",
"foo",
"bar",
"more text"
};
for(int i=0; i < storage.length(); i++){
//Do Something
}
Does this help?
Related
So I have this array List:
private ArrayList<String> output;
Which look like this normally once items are added looks like this:
["ready", "30 min", "5.2 mi", "stop"]
But sometimes the order can change on how the information comes in for example:
["30 min", "stop", "5.2 mi", "ready"]
What would be the best solution to get the number that is in front of mi and min since the ArrayList can change I can't use list.get(1) for example cause the index might be something different.
I have tried to use list.getIndexOf("mi"); but that didn't work, kept coming back as -1 which I would think cause it wasn't an exact match.
Use this .. to get no before "mi"
for(int i =0; i<list.size();i++)
{
if(list.get(i).contains("mi"))
{
String[] splitT =
list.get(i).split(" ");
System.out
.println("before mi is" + splitT[0]);}
}
Note splitT[0] is the answer what you want.. like this you can find for "min" too..
If I understood your question correctly, you want to get an element whith a certain pattern to further work with that information. In that case you could loop through the ArrayList and check for element whether or not it matches a certain regexp. Something like this:
for (String s : arraylist) {
if (s.matches("[0-9]+ mi(n)?")) //would match any number, followed by a whitespace and mi/min {
//do something
}
}
You can do something likes this.
for (String item:list){
if (item.contains("mi")&&!item.contains("min")){
Log.d("item",item.substring(0,3));
}
}
You can do similarly for "min".
You can use this code:
for (int i=0 ; i<output.size() ; i++){
if (output.get(i).endsWith("mi")) // index i contains "mi"
else if (output.get(i).endsWith("min")) //index i contains min not mi
}
I am trying to ignore spaces in editview between text, I am not quite sure how I can go about doing this. I know I can use trim feature to ignore spaces before and after the full text but how do I ignore space between strings if there is any;
String myTextEdited myText.getText().toString().trim();
For example, if I have / user types in this;
Allan Bob
3523 JKO
NY1 U90
I want to ingore spaces when I read this in my if statement or put it in another variable for example;
String name = "AllanBob"
For example, to ignore upper and lower cases I am doing this;
if (myText.getText().toString().trim().equalsIgnoreCase(userInput)) {
// do something
} else {
// do something
}
What I would like to do is add another feature in here that also ignores spaces before, between and after text e.g. instead of;
myname is Henry . (space until here)
It should read it as mynameishenry but to the user it still appears as they have written it.
Please let me know if my question was not clear, I will try explaining it better
EDITED:
is it possible to ignore spaces in string that I have inside my if statement. For example;
if (myText.getText().toString().trim().equalsIgnoreCase("Henry 0887")) {
// do something
} else {
// do something
}
but currently if the user types in henry0887, the if statement does not validate it because I added a space inside my validation text and therefoe its looking for a space in the text, is it possible to over come this, so even if I have space inside my validation it ignores it.
Did you try this:
String myString = myEditText.getText().toString();
myString = myString .replace(" ", "");
Hope it helps
EDIT:
if (myText.getText().toString().replace(" ", "").equalsIgnoreCase(userInput) || myText.getText().toString().equalsIgnoreCase(userInput)) {...
Try this,
if(myText.getText().toString().trim().replace(" ","").equalsIgnoreCase(userInput)) {
// do something
} else {
// do something
}
Hope this helps.
use replaceAll() method.
str = str.replace(" ","");
or for all space chars:
str = str.replace("\\s+","");
EDIT
if (myText.getText().toString().replace("\\s+","").equalsIgnoreCase(userInput)) {
// do something
} else {
// do something
}
EDIT2
if (myText.getText().toString().replace("\\s+","").equalsIgnoreCase("Henry 0887".replace("\\s+",""))) {
// do something
} else {
// do something
}
I'm using the speech recognizer to get a voice input from the user, it returns an array of 5 strings which I pass to this method
public int analyzeTag(ArrayList<String> voiceResults,Editor editor, Context context){
for (String match : voiceResults) {
Log.d(TAG, match);
if (match.equalsIgnoreCase(context.getResources().getString(R.string.first_tag))){
editor.append(context.getResources().getString(R.string.first_tag));
return 1;
}
else if (match.equalsIgnoreCase(context.getResources().getString(R.string.second_tag))){
editor.append(context.getResources().getString(R.string.second_tag));
return 1;
}
//etc....(huge list of tags)
//Some tags might also have acceptable variations, example:
else if (match.equalsIgnoreCase("img") || match.equalsIgnoreCase("image")
{
editor.append("img"); //the string to append is always taken from the first variation
}
}
return 0;
}
This method compares the results with a list of tags, the tag list will be pretty big with hundreds of tags so I would like to find the most efficient way to do this operation.
I need help with:
1.Is my way of comparing results the most efficient? Is there a better way? (from the user experience perspective, I don't want users waiting a long time to get a result).
The voice input will be a big part of my app so this method will be called quite often
2.I have a long list of tags, obviously the if(), elseIf() route is gonna be quite repetitive, is there a way to iterate this? Considering the fact that some tags might have variations (even more than 1)and that the variation 1 ("img") will be the same for everyone, but other variations will be locale/language sensitive example: "image" for english users "immagini" for italian users etc.
Text appended to the editor will be always taken from the first variation
How about puting tags in a StringArray and then iterate though the array ?
String[] tags = context.getResources().getStringArray(R.array.tags);
for (String match : voiceResults) {
for (int index = 0; index < tags.length; index++ ) {
if (match.equalsIgnoreCase(tags[index]) {
editor.append(tags[index]);
}
}
}
Here's the doc on StringArray
I have this code :
String[] whereyoufromarray = {"where", "you", "from"};
for (String whereyoufromstring : whereyoufromarray)
{
if (value.contains(whereyoufromstring)) {
//statement
}
}
But I want that if to only execute the statement if "value" has all of the words included in the array, something like "where are you from?". Currently if value has ONLY one of the words in the array the statement is executed.
I can do this with if (value.contains("where") && value.contains("you") && value.contains ("from")) but this just seems unnecessarily long. There has to be a workaround using arrays that I am missing.
Well, what is it?
p.s.: sorry for poor grammar. i'm suffering from sleep deprivation.
String[] whereyoufromarray = {"where", "you", "from"};
boolean valueContainsAllWordsInArray = true;
for (String whereyoufromstring : whereyoufromarray) {
// If one word wasn't found, the search is over, break the loop
if(!valueContainsAllWordsInArray) break;
valueContainsAllWordsInArray = valueContainsAllWordsInArray &&
value.contains(whereyoufromstring);
}
// valueContainsAllWordsInArray is now assigned to true only if value contains
// ALL strings in the array
For a case like this, I typically implement a function just to make the test. Let's call it containsAll()
public static boolean containsAll(String[] strings, String test)
{
for (String str : strings)
if (!test.contains(str))
return false;
return true;
}
And now you just do
if (containsAll(whereyoufromarray, value))
//statement
String[] whereyoufromarray = {"where", "you", "from"};
int arrayLength = whereyoufromarray.length;
int itemCount = 0;
for(String whereyoufromstring : whereyoufromarray)
{
if(value.contains(whereyoufromstring))
{
itemCount++;
}
}
if (itemCount == arrayLength){
//do your thing here
}
rough idea. I don't have my IDE up to proof this, but basically you can set a counter to = the length of your known array, then check each value in the array to see if it contains a match..if it does, increment another counter. At the end, test your counter to see if it matches the length of your array, so in your example, if itemCount= 3, then all values matched. if it was 2, then one would be missing and your method wouldn't execute.
I have a strange problem in my android app. I must compare two string which are equals. I tried this :
if (raspunsdata.equals(rok)) {
System.out.println("changed ");
} else
System.out.println("no change");
}
but I get always "no change". Before this I have System.out.println for both strings, and both of them have the same value.
I tried also (raspunsdata==rok) and raspunsdata.contentEquals(rok) but I have the same problem. Why? I cant understand this.,...please help...
You might have unwanted white spaces. Might need to use the trim function just to make sure.
if (raspunsdata.trim.equals(rok.trim())) {
System.out.println("changed ");
} else
System.out.println("no change");
}
Btw equals is the correct way to check whether the values are the same.
.equals - compares the values of both objects. If you have 2 Strings with the same characters sets .equals will return true;
== - compares if two objects references are equal.
For example:
String a = "lol";
String b = a;
a == b - will be true.
Try reading: http://www.devdaily.com/java/edu/qanda/pjqa00001.shtml