【问题标题】:how to assign a char to an variable on the base of the size of an ArrayList in Java?java - 如何根据Java中ArrayList的大小将char分配给变量?
【发布时间】:2015-09-21 03:14:37
【问题描述】:

我尝试使长 if 语句更紧凑;原来是这样的:

char x;
if(list.size()== 1){
    x = 'a';
}
if(list.size()== 2){
    x = 'b';
}
if(list.size() == 3){
    x = 'c';
}
if(list.size() == 4){
    x= 'd';
}

是否有可能压缩此代码?

已经谢谢了, 贾里范M

【问题讨论】:

  • char x = (char)('a' + list.size()-1);,适用于az
  • 可以使用switch

标签: java list if-statement arraylist char


【解决方案1】:

作为第一步,我们将代码重构为if-else 级联并备份我们将经常使用的列表大小:

1:

int size = list.size();
char x;
if(size == 1) {
    x = 'a';
} else if(size == 2) {
    x = 'b';
} else if(size == 3) {
    x = 'c';
} else if(size == 4) {
    x = 'd';
} else {
    //undefined
    x = '\0';
}

由于我们仅在这种情况下将列表大小与常量进行比较,我们可以进一步将其转换为 switch 语句:

2:

char x;
switch (list.size()) {
    case 1: x = 'a'; break;
    case 2: x = 'b'; break;
    case 3: x = 'c'; break;
    case 4: x = 'd'; break;
    //undefined
    default: x = '\0'; break;
}

假设这不是一个随机选择的示例,而是真实代码,我们看到我们需要一个函数,该函数接受一个从 1 开始的数字,它输出字母表('a''z')并增加值:

3:

char x;
if(list.isEmpty()) {
    //undefined
    x = '\0';
} else {
    //our function
    x = (char) ('a' + list.size() - 1);
    if(x > 'z') {
        //undefined
        x = '\0';
    }
}

【讨论】:

    【解决方案2】:

    您基本上是将大小映射到字符。它可以更容易地完成:

    x = 'a' + list.size() - 1;
    

    【讨论】:

      【解决方案3】:

      更简单的选择: 使用switch case

      骗子选项:

      char x = (char) ('a' + list.size() - 1);
      

      【讨论】:

      • 这里缺少(char) 演员
      • 我认为您不需要演员表,因为无论如何您都将其分配给 char。
      • + 运算符 char 的结果是 int。您必须将其转换为char,否则无法编译。
      • 1.8_u45 版本中使用javac 不起作用。
      • @BinkanSalaryman,你是对的......当我使用 char x = 'a' + 1 - 1; 时它工作正常......但是当我使用 char x = 'a' + list.size() -1; 它不......奇怪......虽然更新了我的答案...
      【解决方案4】:
      char x;
      int size = list.size();
      if (size >= 1 && size <= 4) {
          x = "zabcd".charAt(size); 
      }
      

      【讨论】:

      • @enkor 是的,它确实提供了问题的答案。问题是如何编写代码,与给定的代码相同,但更紧凑。这怎么不是答案?
      • 好的,从技术上讲,它回答了这个问题。显然,我的评论和道歉并不准确。但是,提供代码的解释会有所帮助,它不会解释您的代码的作用。好的,足够公平的人应该足够聪明,可以从中挑选并弄清楚它在做什么。但我相信这不符合 stackoverflow 的精神。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      • 2011-11-08
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多