某系统的数字密码:比如1983,采用加密方式进行传输, 规则如下:先得到每位数,然后每位数都加上5,再对10求余,最后将所有数字反转,得到一串新数。
public class MethodTest10 {
public static void main(String[] args) {
//1.输入一组数字密码
int[] sz = new int[4];
//给数组写入数字密码
Scanner sc=new Scanner(System.in);
for(int i=0;i<sz.length;i++){
System.out.println("输入的第"+(i+1)+"个数字为:");
int a=sc.nextInt();
sz[i]=a;
}
//输出sz数组的数据
for (int i=0;i<sz.length;i++){
System.out.print(sz[i]);
}
//将sz数组与下面的数组分隔开
System.out.println("");
jm(sz);//调用jm方法
}
//使用方法对数字密码进行加密
public static void jm(int[] a){
for (int i = 0; i <a.length; i++) {
//对数组进行加5,对10求余
a[i]+=5;
a[i]%=10;
}
//输出加5,对10求余后的数组数据
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]);
}
System.out.println("");
//对整组数组进行前后元素交换
int c=0;
for (int i = 0; i < a.length/2; i++) {
c=a[i];
a[i]=a[a.length-1-i]; //0与3进行交换,1与2进行交换
a[a.length-1-i]=c;
}
System.out.print("加密完成后的数字为:");
for (int i = 0; i <a.length; i++) {
System.out.print(a[i]);
}
}
}
通过学习,1.将需要加密的数据长度进行修改:
System.out.println("请输入需要加密的数字个数");
Scanner sc=new Scanner(System.in);
int length= sc.nextInt();
int[] sz = new int[length];
2.将需要打印的数组数据换成方法,节省更多的冗余代码:
//查看数组数据
public static void ck(int[] a){
System.out.print("[");
for (int i = 0; i <a.length; i++) {
System.out.print(i==a.length-1?a[i]:a[i]+",");
}
System.out.println("]");
}
3.将数组进行加五对十求余的步骤可简写成:
a[i]=(a[i]+5)%10;
4.将反转步骤换成(未更改的写法似乎也ok):
for (int i = 0,j=a.length-1; i <j; i++,j--) {
c=a[i];
a[i]=a[j]; //0与3进行交换,1与2进行交换
a[j]=c;
}
即更改后的写法为:
public class MethodTest10 {
public static void main(String[] args) {
//1.输入一组数字密码
System.out.println("请输入需要加密的数字个数");
Scanner sc=new Scanner(System.in);
int length= sc.nextInt();
int[] sz = new int[length];
//给数组写入数字密码
System.out.println("输入的"+length+"个数字为:");
for(int i=0;i<sz.length;i++){
int a=sc.nextInt();
sz[i]=a;
}
System.out.println("查看数组内容:");
ck(sz);
//调用jm
jm(sz);
}
//使用方法对数字密码进行加密
public static void jm(int[] a){
for (int i = 0; i <a.length; i++) {
//对数组进行加5,对10求余
a[i]=(a[i]+5)%10;
}
System.out.println("对数组进行加五,对十求余后:");
ck(a);
//对整组数组进行前后元素交换
int c=0;
for (int i = 0,j=a.length-1; i <j; i++,j--) {
c=a[i];
a[i]=a[j]; //0与3进行交换,1与2进行交换
a[j]=c;
}
System.out.print("加密完成后的数字为:");
ck(a);
}
//查看数组数据
public static void ck(int[] a){
System.out.print("[");
for (int i = 0; i <a.length; i++) {
System.out.print(i==a.length-1?a[i]:a[i]+",");
}
System.out.println("]");
}
}