Now assume that a company uses public phones to transmit data. The data is a four-digit integer and is encrypted during the transmission process.
The encryption rule is to add 5 to each digit, then replace the number with the remainder divided by 10, and then exchange the first and fourth digits, and the second and third digits.
Write a program that receives a four-digit integer and prints out the encrypted number.
This question originally did not require the use of arrays, so we first used a method of translating the question to complete this question. 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 illegal! 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 completion, we will try to use an array to solve this problem. After many attempts, we can implement this function. 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 illegal! 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 core code for using an array to complete this function is only a for loop, and the 4-digit condition in the question can be easily changed to 5-digit or 6-digit or more without too much code changes.
I believe that the examples described in this article will bring certain reference value to learning arrays in Java.