(i) the ancient Roman Emperor Caesar used the following methods to encrypt military intelligence during the war: please write a program that uses the above algorithm to encrypt or decrypt the English string entered by the user.
1. Design idea: The first choice is to encrypt the string or decrypt the string, the two algorithms are similar. If you want to encrypt a string, you need to consider the special character, which is the three characters of XYZ, and the corresponding decryption string, as well as the three characters of ABC.
2. Program Flowchart
3. Source code
ImportJava.util.Scanner; Public classWork1 { Public Static voidMain (string[] args) {//TODO auto-generated Method StubScanner scanner=NewScanner (system.in); intNum=0; System.out.println ("(1 encrypted string, 2 decrypted string)"); System.out.print ("Please select:"); Num=Scanner.nextint (); if(num==1) {System.out.print ("Please enter a string to encrypt:"); String Str=Scanner.next (); Scanner.close ();//What does that mean?
System.out.print ("After encryption:");
CharA= ' a '; for(intI=0;i<str.length (); i++) { CharA2=Str.charat (i); if(a2>= ' A ' &&a2<= ' Z ') { if(a2>= ' X ' &&a2<= ' Z ') { if(a2== ' X ') a= ' a '; if(a2== ' Y ') a= ' B '; if(a2== ' Z ') a= ' C '; } Else{a=(Char) (a2+3);} } System.out.print (a);} } if(num==2) {System.out.print ("Please enter a string to decrypt:"); String Str=Scanner.next (); CharB= ' B ';
System.out.print ("After decryption:"); for(intJ=0;j<str.length (); j + +) {CharB2=Str.charat (j); if(b2>= ' A ' &&b2< ' Z ') { if(b2>= ' A ' &&b2< ' D ') { if(b2== ' A ') b= ' X '; if(b2== ' B ') b= ' Y '; if(b2== ' C ') b= ' Z '; } Else{b=(Char) (b2-3);} } System.out.print (b);} } }}
4. Results
(ii) Hands-on brain
1.string.equals () Method: Compares the contents of a two string.
2.Length (): Gets the length of the string.
3.charAt (): Gets the character at the specified position.
4. GetChars (): Gets the substring copied from the specified position into the character array.
5.replace (): substring substitution.
6.toUpperCase (): All characters are capitalized to return a new string.
7. toLowerCase (): All characters become lowercase, returning a new string.
8.trim (): Remove the kinsoku space.
9.toCharArray (): Converts a String object to a character array.
Java String 05 Course problem Solving