Now suppose a company uses a public telephone to pass data, the data is a four-bit integer and is encrypted during the transfer.
The encryption rule is to add 5 to each digit, then replace the number with the remainder divided by 10, then swap the first and fourth digits, the second and third digits.
Write a program that receives a four-bit integer, and the number of the printed output encrypted.
This question was originally not required to use an array, so we first use a method of translating the problem to complete the problem, the main code is as follows:
public static void Main (string[] args) {
System.out.println ("Please enter a 4-digit number:");
Scanner sc=new Scanner (system.in);
int n=0;
int i=0;
while (true) {
n=sc.nextint ();
if (n<999| | n>10000) {
System.out.println ("The number you entered is not legal!") Please re-enter ");
else{break
;
}
int gewei=n%10;
n/=10;
int shiwei=n%10;
n/=10;
int baiwei=n%10;
n/=10;
gewei+=5;
shiwei+=5;
baiwei+=5;
n+=5;
int a=gewei%10;
int b=shiwei%10;
int c=baiwei%10;
int d=n%10;
int out=d*1000+c*100+b*10+a;
SYSTEM.OUT.PRINTLN ("The encrypted number is:" +out);
}
After we finish, we try to solve the problem with an array and try to implement it after many attempts, and the code is as follows:
public static void Main (string[] args) {
System.out.println ("Please enter a 4-digit number:");
Scanner sc=new Scanner (system.in);
int n=0;
int a=0;
while (true) {
n=sc.nextint ();
if (n<999| | n>10000) {
System.out.println ("The number you entered is not legal!") Please re-enter ");
Else{break}
}
Int[] M=new int[4];
for (int i=0;i<m.length;i++) {
m[i]=n%10;
n/=10;
m[i]+=5;
m[i]%=10;
System.out.print (M[i]);
}
The code that uses an array to complete the core of this function has only a for loop, and the 4-digit number in the title can easily be changed to 5-bit 6-bit or more without requiring too much code change.
It is believed that the example mentioned in this article will bring some reference value to the attack of learning Java arrays.