ROT13.java 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.util.Scanner;
  4. public class ROT13 {
  5. Integer diff;
  6. ROT13(Character cs, Character cf) {
  7. this.diff=Math.abs((int)cs-(int)cf);
  8. }
  9. ROT13() {
  10. this.diff = 13;
  11. }
  12. public String crypt(String text) throws UnsupportedOperationException {
  13. String str="";
  14. for (int i=0; i<text.length(); i++)
  15. {
  16. if(!Character.isLetter(text.charAt(i)))
  17. {
  18. str+=text.charAt(i);
  19. }
  20. else if (Character.isUpperCase(text.charAt(i)))
  21. {
  22. char ch = (char)(((int)text.charAt(i) + diff - 65) % 26 + 65);
  23. str+=ch;
  24. }
  25. else if(Character.isLowerCase(text.charAt(i)))
  26. {
  27. char ch = (char)(((int)text.charAt(i) + diff - 97) % 26 + 97);
  28. str+=ch;
  29. }
  30. }
  31. return str;
  32. }
  33. public String encrypt(String text) {
  34. return crypt(text);
  35. }
  36. public String decrypt(String text) {
  37. return crypt(text);
  38. }
  39. public static String rotate(String string, Character c)
  40. {
  41. Integer diff=(int)c-(int)'A';
  42. return string.substring(diff,string.length())+string.substring(0,diff);
  43. }
  44. public static String encrpttextfile() throws FileNotFoundException {
  45. File file=new File("sonnet18.txt");
  46. Scanner sc=new Scanner(file);
  47. StringBuilder br =new StringBuilder();
  48. while(sc.hasNext())
  49. {
  50. ROT13 rot13=new ROT13();
  51. String str=rot13.crypt(sc.nextLine());
  52. br.append(str+'\n');
  53. }
  54. System.out.println(br);
  55. return br.toString().trim();
  56. }
  57. public static void main(String[] args) throws FileNotFoundException {
  58. encrpttextfile();
  59. }
  60. }