hey yall, i have a long script that lets a user choose a team once they enter a set of characters. it goes through a long list of if else statements in order to choose it. are there any other commands that would be more fitting? Here is my current code:
if (finalChar.equals("aa") == true) {
r = 151;
g = 35;
b = 63;
title = "Arizona Cardinals Time!";
imageSelected = "cardinals";
} else {
if (finalChar.equals("ab") == true) {
r = 151;
g = 35;
b = 63;
title = "Atlanta Falcons Time!";
imageSelected = "falcons";
} else {
if (finalChar.equals("ac") == true) {
r = 26;
g = 25;
b = 95;
title = "Baltimore Ravens Time!";
imageSelected = "ravens";
} else {
if (finalChar.equals("ad") == true) {
r = 0;
g = 51;
b = 141;
rh = 198;
gh = 12;
bh = 48;
title = "Buffalo Bills Time!";
imageSelected = "bills";
} else {
any help will be appreciated
EDIT: i forgot to mention, but the code continues to go on, and it repeats over and over about 30 more times. sorry lol
This would be far better done with a table lookup rather than a long code string of tests. Either use a simple indexed array or, if you need your string lookup, use a HashMap.
I concur with @bryan and @scudly that a lookup table is probably the best solution here.
Although for the example cases a little reorganization can simplify things somewhat. If you always check the last two characters, then you can test the length, then extract the last two characters, check the first with if/elseif and nest switch statements. It’s not vastly different, but adds less if/elseif visual mess and so is potentialyl slightly more readable.
String str = "vlad";
if( str.length() >= 2) {
final char one = str.charAt( str.length() - 2 );
final char two = str.charAt( str.length() - 1 );
if( one == 'a' ) {
switch(two) {
case 'a': break;
case 'b': break;
case 'c': break;
case 'd': break;
default: break;
}
}
}
As an addendum though, if anyone is still wondering, Java does support String “constants” for switch cases as of Java/JDK 7 (aka 1.7). Also, although Java String variables are technically immutable, you must either use final variables or quoted strings (e.g. “testcase”) because they are re-assignable.
Taking advantage of that, a more straightforward switch block can be devised.
switch(test) {
case "aa": doStuff(); break;
case "ab": doStuff(); break;
case "ac": doStuff(); break;
case "ad": doStuff(); break;
//....
default: break;
}
HashMap<String,Team> hm = new HashMap<String,Team>();
Team tm = new Team("ad", 0, 51, 141, "Buffalo Bills Time", "bills");
hm.put("ad", tm);
// get the team later
Team selected = hm.get(finalChar); // "ad"
println(selected.title); // prints "Buffalo Bills Time"