有人对如何使这个Java switch案例更高效/更可读有什么建议吗?

有人对如何使这个Java switch案例更高效/更可读有什么建议吗?,java,performance,syntax,switch-statement,Java,Performance,Syntax,Switch Statement,这是一个相当标准的开关盒,用于复制电路的程序中。我要寻找的主要东西是代码的可读性和简洁性,而不忽略效率 编辑:没有意识到我不清楚偏移量的用途,偏移量的工作方式是将输入字符偏移一个等于偏移量的字符数,偏移量是一个整数。因此,例如,如果源为“a”,偏移量为2,则将返回索引2处路径数组中的值 char passCurrent(char source) { source += offset; switch(source) { case 'a':

这是一个相当标准的开关盒,用于复制电路的程序中。我要寻找的主要东西是代码的可读性和简洁性,而不忽略效率

编辑:没有意识到我不清楚偏移量的用途,偏移量的工作方式是将输入字符偏移一个等于偏移量的字符数,偏移量是一个整数。因此,例如,如果源为“a”,偏移量为2,则将返回索引2处路径数组中的值

char passCurrent(char source)
 {
     source += offset;

     switch(source)
     {
     case 'a':
         return this.paths[0];
     case 'b':
         return this.paths[1];
     case 'c':
         return this.paths[2];
     case 'd':
         return this.paths[3];
     case 'e':
         return this.paths[4];
     case 'f':
         return this.paths[5];
     case 'g':
         return this.paths[6];
     case 'h':
         return this.paths[7];
     case 'i':
         return this.paths[8];
     case 'j':
         return this.paths[9];
     case 'k':
         return this.paths[10];
     case 'l':
         return this.paths[11];
     case 'm':
         return this.paths[12];
     case 'n':
         return this.paths[13];
     case 'o':
         return this.paths[14];
     case 'p':
         return this.paths[15];
     case 'q':
         return this.paths[16];
     case 'r':
         return this.paths[17];
     case 's':
         return this.paths[18];
     case 't':
         return this.paths[19];
     case 'u':
         return this.paths[20];
     case 'v':
         return this.paths[21];
     case 'w':
         return this.paths[22];
     case 'x':
         return this.paths[23];
     case 'y':
         return this.paths[24];
     case 'z':
         return this.paths[25];
     }
     return '/';
 }

消除
开关
并在检查范围后使用减法。大概

if (source >= 'a' && source <= 'z') {
    return this.paths[source - 'a'];
}
return '/';

if(source>='a'&&source='a'&&sourcea
char
只是一个数字;数字的含义与字符在Unicode中的排列方式有关(0到127之间的数字很久以前由ASCII定义,后来被纳入Unicode)

因此,如果
source
'a'
,它实际上有整数值97。从
a
z
的字母在Unicode中都是连续的,因此
b
是98,
c
是99,等等

这意味着,如果你想要0代表
a
,1代表
b
,等等,你可以通过简单的减法得到它。因此:

if (source >= 'a' && source <= 'z') {
    return this.paths[source - 97];
}

if(source>='a'&&source='a'&&source您可能会在codereview.stackexchange.com上获得更好的结果。发布源和偏移量声明,如果它们是字符串,那么如何使用char is switch?@SotiriosDelimanolis原样,在缺少上下文的情况下会收到较差的效果。
路径
没有定义,我们不知道是什么在
源代码
来自(或其目的)或该
偏移量
可能是什么,或者为什么我们要处理字母表中的字母,以及它是否是解决该代码正在解决的实际问题的好方法。这说明了问题的形式(例如,“寻求提高可读性+效率”)确实看起来像是一个CR问题,它在堆栈溢出问题上是离题的。@markspace这是一个我希望从没有意识到
char
是一种整数的人那里得到的问题。我猜这在新程序员中是相当大的一部分。除非你在什么地方学过它,否则这不明显。这似乎是一个合法的任务对我来说,@ajb的东西是,
偏移量
是相关的。如果它的值是97(
'a'
),那么开关或减法中就没有点了,只要
返回这个。路径[源代码]
…很好地解释了为什么要这样做,我只选择了另一个答案,因为三元运算符使代码更干净。没有问题。我自己可能也用过三元运算符,但这是风格问题——我知道程序员不喜欢三元运算符。
if (source >= 'a' && source <= 'z') {
    return this.paths[source - 97];
}
if (source >= 'a' && source <= 'z') {
    return this.paths[source - 'a'];
}