如何在处理中压缩嵌套的“ if else”语句?

时间:2019-02-15 14:45:56

标签: processing

我有一个很长的脚本,一旦输入一组字符,用户就可以选择一个团队。它会通过一长串if else语句来选择它。还有其他更合适的命令吗?这是我当前的代码:

 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 {
if (finalChar.equals("ae") == true) {
r = 0;
g = 133;
b = 202;
        rh = 16;
        gh = 24;
        bh = 32;
        title = "Carolina Panthers Time!";
        imageSelected = "panthers";
      } else {
        if (finalChar.equals("af") == true) {
          r = 11;
          g = 22;
          b = 42;
          rh = 200;
          gh = 56;
          bh = 3;
          title = "Chicago Bears Time!";
          imageSelected = "bears";
        } else {
          if (finalChar.equals("ag") == true) {
            r = 251;
            g = 79;
            b = 20;
            rh = 0;
            gh = 0;
            bh = 0;
            title = "Cincinnati Bengals Time!";
            imageSelected = "bengals";
          } else {
            if (finalChar.equals("ah") == true) {
              r = 49;
              g = 29;
              b = 0;
              rh = 255;
              gh = 60;
              bh = 0;
              title = "Cleveland Browns Time!";
              imageSelected = "browns";
            } else {
              if (finalChar.equals("ai") == true) {
                r = 0;
                g = 34;
                b = 68;
                title = "Dallas Cowboys Time!";
                imageSelected = "cowboys";
              } else {

任何帮助将不胜感激

我忘记提了,但是代码继续进行,并且重复了30多次。对不起,哈哈

1 个答案:

答案 0 :(得分:1)

  1. 查看DRY
  2. 学习如何use an array的字符串
  3. 了解如何do a for loop遍历数组中的每个字符串并检查条件

例如

String[] suffixes = {"aa","ab","ac","ad","ae","af","ag","ah","ai"};
for(int i = 0 ; i < suffixes.length; i++){
 println(suffixes[i]); 
}

根据需要如何处理这些字符串,处理中还有一个String Dictionary,它允许您将一个字符串与另一个字符串关联。 (如果您搜索字符串列表,这可能比循环和比较更有效)

请确保遍历数组和循环,如果您选择对数据使用其他结构,这将很方便。

例如,您可以将其表示为JSON对象(Processing通过JSONObject支持该对象):

{
  "aa": {
    "r" : 151,
    "g" : 35,
    "b" : 63,
    "title" : "Arizona Cardinals Time!",
    "imageSelected" : "cardinals"
  },
  "ab": {
    "r" : 151,
    "g" : 35,
    "b" : 63,
    "title" : "Atlanta Falcons Time!",
    "imageSelected" : "falcons"
  },
  "ac": {
    "r" : 26,
    "g" : 25,
    "b" : 95,
    "title" : "Baltimore Ravens Time!",
    "imageSelected" : "ravens"
  }
}

...等等。