文章目录
一、需求
数字密码加密:比如1983,采用加密方式传输,规则如下:
先得到每位数,然后每位数加上5再对10求余,最后将所有数字反转,得到一串新的数字
明文 1 9 8 3
+5 6 14 13 8
%10 6 4 3 8
反转 8 3 4 6
加密过后的结果是:8346
二、分析
1.将每位数据存入到数组中,遍历数组每位数据按照规则进行更改,把更改后的数据重新存入到数组中。
2.将数组的前后元素进行交换,数组中的最终元素就是加密后的结果。
三、代码
import java.util.Scanner;
/**
* 某系统的数字密码:比如1983,采用加密方式进行传输,规则如下:先得到每位数,然后每位数都加上5
* 再对10求余,最后将所有数字反转,得到一串新数
* 明文 1 9 8 3
* +5 6 14 13 8
* %10 6 4 3 8
* 反转 8 3 4 6
* 加密过后的结果是:8346
*/
public class CaseDemo6 {
/**
* 分析:
* 将每位数据存入到数组中去,遍历数组每位数据按照规则进行更改,把更改后的数据重新存入到数组中
* 将数组的前后元素进行交换,数组中的最终元素就是加密后的结果
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入密码位数:");
int n = sc.nextInt();
int[] password = new int[n];
getPassword(password);
encryptPassword(password);
printEncryptPassword(password);
}
public static void getPassword(int[] password) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入密码(以空格分割):");
for (int i = 0; i < password.length; i++) {
int m = sc.nextInt();
password[i] = m;
}
}
public static void encryptPassword(int[] password) {
for (int i = 0; i < password.length; i++) {
password[i] = (password[i] + 5) % 10;
}
//反转 index: start end start < end 就交换
int startIndex = 0;
int endIndex = password.length - 1;
int temp;
for (int j = 0; j < password.length; j++) {
if (startIndex < endIndex) {
temp = password[startIndex];
password[startIndex] = password[endIndex];
password[endIndex] = temp;
}
startIndex++;
endIndex--;
}
}
public static void printEncryptPassword(int[] password) {
System.out.print("[");
for (int i = 0; i < password.length; i++) {
System.out.print(i == password.length - 1 ? password[i] : password[i] + ",");
}
System.out.println("]");
}
}
效果图
总结
如何完成数组元素的反转
1.定义两个变量分别占数组的首尾。
2.一个变量往前走,一个变量往后走,同步交换双方位置处的值。