• Source
    1.  
    2. class Main {
    3. public static void main (String[] args) throws java.lang.Exception
    4. {
    5. System.out.println(cifra(3, "INVIO RINFORZI"));
    6. System.out.println(decifra(3, "IIIOINONR VRFZ "));
    7. }
    8.  
    9. public static String cifra(int key, String messaggio) {
    10. int c = key;
    11. String output = "";
    12. messaggio = messaggio.replaceAll("\\s", "");
    13.  
    14. int r = messaggio.length()/c;
    15. if (messaggio.length()%c != 0){
    16. r++;
    17. }
    18. int pos = 0;
    19.  
    20. char[][] M = new char [r][c];
    21. System.out.println("Matrice cifratura:");
    22. for (int i = 0; i < r; i++) {
    23. for (int j = 0; j < c; j++) {
    24. if (pos == messaggio.length())
    25. break;
    26. M[i][j] = messaggio.charAt(pos);
    27. System.out.print(M[i][j]+" ");
    28. pos++;
    29. }
    30. System.out.println();
    31. }
    32.  
    33. for (int i = 0; i < c; i++) {
    34. for (int j = 0; j < r; j++) {
    35. output += M[j][i];
    36. }
    37. }
    38. return output;
    39. }
    40.  
    41. public static String decifra(int key, String messaggio) {
    42. int c = key;
    43. String output = "";
    44.  
    45. messaggio = messaggio.replaceAll("\\s", "");
    46.  
    47. int r = messaggio.length()/c;
    48. if (messaggio.length()%c != 0){
    49. r++;
    50. }
    51. int pos = 0;
    52.  
    53. char[][] M = new char [r][c];
    54. System.out.print("righe: "+r+" | "+"colonne: "+c);
    55. System.out.println("\nMatrice decifratura:");
    56. for (int j = 0; j < r; j++) {
    57. for (int i = 0; i < c; i++) {
    58. if (pos == messaggio.length())
    59. break;
    60. M[j][i] = messaggio.charAt(pos);
    61. System.out.print(M[j][i]+" ");
    62. pos++;
    63. }
    64. System.out.println();
    65. }
    66.  
    67. for (int i = 0; i < r; i++) {
    68. for (int j = 0; j < c; j++) {
    69. output += M[i][j];
    70. }
    71. }
    72. return output;
    73. }
    74.  
    75. }
    76.