user3051460 user3051460 - 1 month ago 5
Java Question

How to compare a element in String array in Android?

I have a String arrays as follows:

String [] str_cmd_arr={"cmd1", "cmd2"};


Given that, "cmd1" will has output is "perform command 1", while "cmd2" will has output is "perform command 2".

From my
str_cmd_arr
, how can I print the outputs individually in Java/Android? Currently, I am using the code

for (int i=0;i<str_cmd_arr.length;i++){
if(i<1){
Log.d("TAG","perform command 1");
}
else{
Log.d("TAG","perform command 2");
}
}

Answer

The real solution here: use a Map, like

Map<String, String> commandsAndOutput = new HashMap<>();
commandsAndOutput.put("cmd1", "cmd1 output");
...

to later do

String output = commandsAndOutput.get("cmd1");

for example.

Another, probably more sane way here: consider using enums, like:

public enum Command {
  CMD1, CMD2;
}

if you are looking for more "compile time" support when making choices between different commands. As you now can write down:

Command cmd = ...
switch(cmd) {
  case(CMD1) : ...

But another word of warning: one should be careful about such enum/switching code. In most situations, a "real OO based" design that works with an abstract base class Command and specific subclasses is the better choice.

The real lesson here: you want to study some basics, like the tutorials found here. You see, there is no point in programming for Android ... if you don't know about such basic things such as Maps. In that sense it is hard to give you "good" advise, as the "good" stuff would that abstract base class solution - which seems to be completely beyond your current skills.

Comments