123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 fact = 1;
  11. for (int i = 1; i <= number; i++) {
  12. fact = fact*i;
  13. }
  14. return fact;
  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 sb = new StringBuilder();
  25. for (String s : phrase.split(" ")){
  26. s = s.toUpperCase();
  27. sb.append(s.charAt(0));
  28. }
  29. return sb.toString();
  30. }
  31. /**
  32. * To prevent anyone from reading our messages, we can encrypt it so it will only be readable by its
  33. * intended audience. This method encrypt the message by shifting the letter by 3 characters. If the character is
  34. * at the end of the alphabet, it will wraps around.
  35. * For example:
  36. * 'a' => 'd'
  37. * 'w' => 'z'
  38. * 'x' => 'a'
  39. * 'y' => 'b'
  40. * @param word
  41. * @return the encrypted string by shifting each character by three character
  42. */
  43. public String encrypt(String word) {
  44. int shift = 3;
  45. String s = "";
  46. int len = word.length();
  47. for (int x = 0; x < len; x++){
  48. char c = (char)(word.charAt(x) + shift);
  49. if (c > 'z')
  50. s += (char)(word.charAt(x) - (26-shift));
  51. else
  52. s += (char)(word.charAt(x) + shift);
  53. }
  54. return s;
  55. }
  56. }