12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. public class LoopFun
  2. {
  3. /**
  4. * Given a number, return the factorial of that number.
  5. * For example, given 5, the factorial is 5 x 4 x 3 x 2 x 1 which should return 120.
  6. * @param number
  7. * @return the factorial of the number
  8. */
  9. public int factorial(int number){
  10. int counter = number;
  11. for (int i = number - 1; i > 1; i --) {
  12. counter = counter * i;
  13. }
  14. return counter;
  15. }
  16. /**
  17. * Given a phrase, get the acronym of that phrase. Acronym is the combination of
  18. * the first character of each word in upper case.
  19. * For example, given "Ruby on Rails", this method will return "ROR"
  20. * @param phrase
  21. * @return Upper case string of the first letter of each word
  22. */
  23. public String acronym(String phrase) {
  24. String upperAcro = "";
  25. String[] words = phrase.split(" ");
  26. // cycle through and grab each char @ 0 and return to string
  27. for (int i = 0; i < words.length; i++) {
  28. upperAcro += Character.toString(words[i].charAt(0));
  29. }
  30. return upperAcro.toUpperCase();
  31. }
  32. /**
  33. * To prevent anyone from reading our messages, we can encrypt it so it will only be readable by its
  34. * intended audience. This method encrypt the message by shifting the letter by 3 characters. If the character is
  35. * at the end of the alphabet, it will wraps around.
  36. * For example:
  37. * 'a' => 'd'
  38. * 'w' => 'z'
  39. * 'x' => 'a'
  40. * 'y' => 'b'
  41. * @param word
  42. * @return the encrypted string by shifting each character by three character
  43. */
  44. public String encrypt(String word) {
  45. // encoder of full alphabet
  46. String encoder = "abcdefghijklmnopqrstuvwxyz";
  47. String decryptMessage = "";
  48. int encodeMove = 3;
  49. // nested for loop to check chars to chars of the string
  50. for (int i = 0; i < word.length(); i++){
  51. // this loop checks char @ i and compares to the encoder string
  52. for (int j = 0; j < encoder.length(); j++) {
  53. // cycles through encoder and finds the position in the encoder
  54. // loops back to front, if j == encoder.length();
  55. // j = 0
  56. if (word.charAt(i) == (encoder.charAt(j))) {
  57. if (j >= 23) {
  58. int k = j;
  59. int end = encoder.length() - 1;
  60. // add until it hits 26, then reinitialize to -1 (for case "x" it should be at index 0)
  61. for (int l = 0; l <= 2; l++) {
  62. if ( k == end ) {
  63. k = -1;
  64. }
  65. k ++;
  66. }
  67. decryptMessage += Character.toString(encoder.charAt(k));
  68. } else {
  69. decryptMessage += Character.toString(encoder.charAt(j+3));
  70. }
  71. }
  72. }
  73. }
  74. // if statement to wrap around
  75. return decryptMessage;
  76. }
  77. }