1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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=1; 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. String[] acronym = phrase.split(" ");
  25. String newStr = " ";
  26. for (int i = 0; i < acronym.length; i++) {
  27. String s = acronym[i];
  28. newStr += s.charAt(0);
  29. }
  30. return newStr.replace(" ","").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. char[] arr = new char[word.length()];
  46. for (int i = 0; i < arr.length; i++) {
  47. if(word.charAt(i) == 'x'){
  48. arr[i] = 'a';
  49. } else if (word.charAt(i) == 'y'){
  50. arr[i] = 'b';
  51. } else if (word.charAt(i) == 'z'){
  52. arr[i] = 'c';
  53. }else {
  54. arr[i] = (char) (word.charAt(i) + 3);
  55. }
  56. }
  57. String result = new String(arr);
  58. return result;
  59. }
  60. }