您可以根据计算中的单行 if 语句进行加法或减法吗?
Can you either add or subtract based on a one-line if-statement inside a calculation?
(Java)
问题的措辞有点困难,但这就是我的意思:
我一直在研究一个简单的 Ceasar 密码,根据是加密还是解密,应该添加或减去密钥 to/from 与字符关联的值。因此,这就是我想出的:
// if direction == true, shift forwards (encrypt), else shift backwards (decrypt)
if (direction == true) {
newPos = (character - 'a' + key) % 26 + 'a';
} else if (direction == false) {
newPos = (character - 'a' - key) % 26 + 'a';
}
但我想知道是否可以缩短它,以便它根据是否应该加密或解密在计算中放置一个“-”或“+”符号,例如:(我知道下面的代码不起作用,但它说明了我的意思)
// if direction == true, place a '+', else place a '-'
newPos = (character - 'a ' ((direction == true) ? + : -) key) % 26 + 'a';
所以我想知道在Java中是否有任何方法可以做这样的事情?我不确定这是否会对保持我的代码清洁有巨大好处,但我认为它可能有助于消除代码中的一些重复。到目前为止,我一直无法在网上找到这个问题的答案。
编辑:我不一定需要针对上述情况的解决方案(这正是我遇到该主题的方式),但我的意思是 post 是一个更普遍的问题,关于是否这将是可能的,并且如何。
您不能 return 运算符,但可以 return 正值或负值:
'a' + ((direction == true) ? key : -key)
也可以写成:
'a' + (direction ? key : -key)
或者您可以将方向更改为 int:+1 或 -1 并仅使用乘法:
'a' + direction * key
(Java) 问题的措辞有点困难,但这就是我的意思:
我一直在研究一个简单的 Ceasar 密码,根据是加密还是解密,应该添加或减去密钥 to/from 与字符关联的值。因此,这就是我想出的:
// if direction == true, shift forwards (encrypt), else shift backwards (decrypt)
if (direction == true) {
newPos = (character - 'a' + key) % 26 + 'a';
} else if (direction == false) {
newPos = (character - 'a' - key) % 26 + 'a';
}
但我想知道是否可以缩短它,以便它根据是否应该加密或解密在计算中放置一个“-”或“+”符号,例如:(我知道下面的代码不起作用,但它说明了我的意思)
// if direction == true, place a '+', else place a '-'
newPos = (character - 'a ' ((direction == true) ? + : -) key) % 26 + 'a';
所以我想知道在Java中是否有任何方法可以做这样的事情?我不确定这是否会对保持我的代码清洁有巨大好处,但我认为它可能有助于消除代码中的一些重复。到目前为止,我一直无法在网上找到这个问题的答案。
编辑:我不一定需要针对上述情况的解决方案(这正是我遇到该主题的方式),但我的意思是 post 是一个更普遍的问题,关于是否这将是可能的,并且如何。
您不能 return 运算符,但可以 return 正值或负值:
'a' + ((direction == true) ? key : -key)
也可以写成:
'a' + (direction ? key : -key)
或者您可以将方向更改为 int:+1 或 -1 并仅使用乘法:
'a' + direction * key