你好,对于一个项目,我必须加密和解密一个txt文件。一切都运行得很好,程序完全按照我想要的方式运行,我只是好奇是否有办法简化其中的一部分
int first;
int second;
int third;
int fourth;
long M = 0;
if (toDecrypt.length() == 4) {
first = ((toDecrypt.charAt(0) - '0') * 1000);
second = ((toDecrypt.charAt(1) - '0') * 100);
third = ((toDecrypt.charAt(2) - '0') * 10);
fourth = toDecrypt.charAt(3) - '0';
M = first + second + third + fourth;
}
if (toDecrypt.length() == 3) {
first = ((toDecrypt.charAt(0) - '0') * 100);
second = ((toDecrypt.charAt(1) - '0') * 10);
third = toDecrypt.charAt(2) - '0';
M = first + second + third;
}
if (toDecrypt.length() == 2) {
first = ((toDecrypt.charAt(0) - '0') * 10);
second = toDecrypt.charAt(1) - '0';
M = first + second;
}
long temp = M;这一节所做的是逐行接收我的加密文件,这些文件是以数字形式存在的,并将其解密。每条线路可以有2-4个数字。就像我说的,代码工作得很好,我只是好奇我是否能够简化它,或者如果我想太多了,如果它工作了,就不要费心去改变它了。我想我在这里的总体问题是,在现实世界中,程序员/程序员是否试图使他们的程序变得更简单,或者是首先有效的选项就是他们所采用的吗?
发布于 2017-02-08 11:05:26
这样如何:
long M = 0;
int hash = 1;
for(int i = toDecrypt.length() - 1 ; i >= 0; i--)
{
M += (toDecrypt.charAt( i ) - '0') * hash;
hash *= 10;
}但是,如果您只是想从文件中读取数字,您是否考虑过使用Scanner之类的东西?您可以使用nextInt()函数从文件中获取每个数字。看起来你的循环只是把一个String转换成一个数字,对吧?
https://stackoverflow.com/questions/42103820
复制相似问题