1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 factorial = 1;
  11. for (int i = 2; i <= number; i++) {
  12. factorial *= i;
  13. }
  14. return factorial;
  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. StringBuilder sbAcronym = new StringBuilder();
  25. String firstCapital = phrase.substring(0, 1).toUpperCase();
  26. sbAcronym.append(firstCapital);
  27. for (int i = 1; i < phrase.length(); i++) {
  28. if (phrase.charAt(i) == ' ') {
  29. sbAcronym.append(phrase.charAt(i + 1));
  30. }
  31. }
  32. String Acronym = sbAcronym.toString().toUpperCase();
  33. return Acronym;
  34. }
  35. /**
  36. * To prevent anyone from reading our messages, we can encrypt it so it will only be readable by its
  37. * intended audience. This method encrypt the message by shifting the letter by 3 characters. If the character is
  38. * at the end of the alphabet, it will wraps around.
  39. * For example:
  40. * 'a' => 'd'
  41. * 'w' => 'z'
  42. * 'x' => 'a'
  43. * 'y' => 'b'
  44. * @param word
  45. * @return the encrypted string by shifting each character by three character
  46. */
  47. public String encrypt(String word) {
  48. // char[] toEncode = word.toCharArray();
  49. StringBuilder sbEncryption = new StringBuilder();
  50. char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
  51. for (int i = 0; i < word.length(); i++) {
  52. for (int j = 0; j < 26; j++) {
  53. if (word.charAt(i) == arr[j]){
  54. if (j < 23) {
  55. sbEncryption.append(arr[(j + 3)]);
  56. } else {
  57. continue;
  58. }
  59. }
  60. }
  61. }
  62. for (int i = 0; i < 26; i++) {
  63. for (int j = 0; j < word.length(); j++) {
  64. if (word.charAt(j) == arr[i]){
  65. if (i >= 23) {
  66. sbEncryption.append(arr[(i - 23)]);
  67. } else {
  68. continue;
  69. }
  70. }
  71. }
  72. }
  73. String encryption = sbEncryption.toString();
  74. return encryption;
  75. }
  76. }